2011-01-21 4 views
0

これ以外にも、タイプがアクション<>代理人のいずれかであるかどうかを判断する良い方法があります。タイプがAction/Funcデリゲートの1つであるかどうかを判断する方法?

if(obj is MulticastDelegate && obj.GetType().FullName.StartsWith("System.Action")) 
{ 
    ... 
} 
+4

"type"はタイプオブジェクトではなく、タイプが問題のオブジェクトのインスタンスですか?これは、変数に名前を付けるのは非常に誤解を招くようなものです。 –

+0

@エリック:あなたは正しいです、私は何かを試していました、通常、私はそれのように名前をつけませんでした。 – epitka

答えて

9

これは完全に簡単なようです。

static bool IsAction(Type type) 
{ 
    if (type == typeof(System.Action)) return true; 
    Type generic = null; 
    if (type.IsGenericTypeDefinition) generic = type; 
    else if (type.IsGenericType) generic = type.GetGenericTypeDefinition(); 
    if (generic == null) return false; 
    if (generic == typeof(System.Action<>)) return true; 
    if (generic == typeof(System.Action<,>)) return true; 
    ... and so on ... 
    return false; 
} 

なぜこのことを知りたいのか不思議です。特定のタイプがアクションのバージョンの1つである場合、あなたは何を気にしますか?あなたはその情報で何をするつもりですか?

+0

私は "Clay"ライブラリを使って遊んでいます。私は、動的ClayオブジェクトにAction/Funcタイプのプロパティを付けたいと思っています。長い話.. – epitka

1
private static readonly HashSet<Type> _set = new HashSet<Type> 
    { 
     typeof(Action), typeof(Action<>), typeof(Action<,>), // etc 
     typeof(Func<>), typeof(Func<,>), typeof(Func<,,>),  // etc 
    }; 

// ... 

Type t = type.GetType(); 
if (_set.Contains(t) || 
    (t.IsGenericType && _set.Contains(t.GetGenericTypeDefinition()))) 
{ 
    // yep, it's one of the action or func delegates 
} 
関連する問題