Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/338.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/23.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#_.net_.net Core_Instantiation - Fatal编程技术网

C# 如何测试类型是否可实例化?

C# 如何测试类型是否可实例化?,c#,.net,.net-core,instantiation,C#,.net,.net Core,Instantiation,我有类型T,我想检查传递到Activator.CreateInstance(T)是否安全 我想到的是这样做: if(!T.IsInterface && !T.IsAbstract) { instance = (T)Activator.CreateInstance(T); } 但是: 这够了吗?我没有错过必要的考试吗?类型是否可能不是接口,也不是抽象类,但仍然无法实例化?鉴于我对C#的了解还相当初级,我认为我很可能错过了一两个角球 我必须手动编写测试吗?语言中是否包含类

我有类型
T
,我想检查传递到
Activator.CreateInstance(T)
是否安全

我想到的是这样做:

if(!T.IsInterface && !T.IsAbstract)
{
    instance = (T)Activator.CreateInstance(T);
}
但是:

  • 这够了吗?我没有错过必要的考试吗?类型是否可能不是接口,也不是抽象类,但仍然无法实例化?鉴于我对C#的了解还相当初级,我认为我很可能错过了一两个角球
  • 我必须手动编写测试吗?语言中是否包含类似于
    T.isinstatable
    的内容
编辑:否,
T
不是来自一般约束。这是一段代码
T
来自:

var instances = System.Reflection.Assembly.GetExecutingAssembly().GetTypes()
    .Where(
        // some other constraints
    ).Where(
        // can be instantiated, I'm trying to figure this part in my question
    ).Select(
        T => Activator.CreateInstance(T)
    );

如果
T
是泛型参数,只需对其使用
new()
约束即可。这样,编译器将强制执行此操作,而不是运行时

@RyanWilson是的,确切地说,我告诉过你我肯定错过了一些东西:)而且,需要一个没有任何参数的构造函数。私有构造函数呢?您不能在这些类自己的方法之外实例化它们。
如果(t.GetConstructor(Type.EmptyTypes)!=null&&!t.isastract)
应该这样做。这将检查以确保类不是抽象的,它将检查以确保有一个空构造函数。@gaazkam我对静态的看法是错误的,静态类是以抽象和密封的形式返回的,但这里还有其他一些优点,比如关于私有构造函数。这篇文章看起来会给你所需要的一切
T
来自
System.Reflection.Assembly.GetExecutionGassembly().GetTypes().Where(/*otherconstraints*/).Where(/*canBeInstantiated*/)。选择(T=>Activator.CreateInstance(T)
@gaazkam k。这很公平,但那时您将无法强制转换它。