Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-mvc/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何确定类型是否为操作/函数委托之一?_C#_Types - Fatal编程技术网

C# 如何确定类型是否为操作/函数委托之一?

C# 如何确定类型是否为操作/函数委托之一?,c#,types,C#,Types,除此之外,还有更好的方法来确定类型是否是动作委托之一 if(obj is MulticastDelegate && obj.GetType().FullName.StartsWith("System.Action")) { ... } private static readonly HashSet\u set=new HashSet { typeof(Action)、typeof(Action)、typeof(Action)、等 typeof(Func),typeof(F

除此之外,还有更好的方法来确定类型是否是动作委托之一

if(obj is MulticastDelegate && obj.GetType().FullName.StartsWith("System.Action"))
{
   ...
}
private static readonly HashSet\u set=new HashSet
{
typeof(Action)、typeof(Action)、typeof(Action)、等
typeof(Func),typeof(Func),typeof(Func),//等
};
// ...
Type t=Type.GetType();
if(_set.Contains(t)||
(t.IsGenericType&&u set.Contains(t.GetGenericTypeDefinition()))
{
//是的,这是一个行动或职能代表
}

这似乎非常简单

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;
}
静态布尔IsAction(类型)
{
if(type==typeof(System.Action))返回true;
类型generic=null;
if(type.IsGenericTypeDefinition)generic=type;
else如果(type.IsGenericType)generic=type.GetGenericTypeDefinition();
if(generic==null)返回false;
if(generic==typeof(System.Action))返回true;
if(generic==typeof(System.Action))返回true;
等等
返回false;
}

我很好奇你为什么想知道这个。如果某个特定类型恰好是Action的一个版本,您关心什么?您将如何处理这些信息?

这里的“类型”不是类型对象,而是类型有问题的对象的实例?给变量命名似乎是一件很容易引起误解的事情。@Eric:你是对的,我在尝试一些东西,通常我不会这样命名。我正在玩一个“Clay”库,我想将Action/Func类型属性附加到动态Clay对象上。说来话长..检查
type.BaseType==typeof(MulticastDelegate)
就足够了吗?@AshleyF:我没有遵循你的思路。问题在于识别操作和func委托,而不是识别任何委托。你能澄清这个问题吗?]
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;
}