これ以外にも、タイプがアクション<>代理人のいずれかであるかどうかを判断する良い方法があります。タイプがAction/Funcデリゲートの1つであるかどうかを判断する方法?
if(obj is MulticastDelegate && obj.GetType().FullName.StartsWith("System.Action"))
{
...
}
これ以外にも、タイプがアクション<>代理人のいずれかであるかどうかを判断する良い方法があります。タイプがAction/Funcデリゲートの1つであるかどうかを判断する方法?
if(obj is MulticastDelegate && obj.GetType().FullName.StartsWith("System.Action"))
{
...
}
これは完全に簡単なようです。
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つである場合、あなたは何を気にしますか?あなたはその情報で何をするつもりですか?
私は "Clay"ライブラリを使って遊んでいます。私は、動的ClayオブジェクトにAction/Funcタイプのプロパティを付けたいと思っています。長い話.. – epitka
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
}
"type"はタイプオブジェクトではなく、タイプが問題のオブジェクトのインスタンスですか?これは、変数に名前を付けるのは非常に誤解を招くようなものです。 –
@エリック:あなたは正しいです、私は何かを試していました、通常、私はそれのように名前をつけませんでした。 – epitka