Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/335.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# 尝试调用函数<;T>;其中T:TheClass,new()在其中T:class_C#_Generics - Fatal编程技术网

C# 尝试调用函数<;T>;其中T:TheClass,new()在其中T:class

C# 尝试调用函数<;T>;其中T:TheClass,new()在其中T:class,c#,generics,C#,Generics,这是我需要做的一个简化版本。在它目前的状态下,我试图做的没有意义。然而,它以一种简单的方式显示了这个问题 我需要在函数1()中调用函数2(),其中T:class,new(),其中T:class Something<T> function1<T>() where T : class { //cannot call function2 directly due to compile error //return function2<T>(); //W

这是我需要做的一个简化版本。在它目前的状态下,我试图做的没有意义。然而,它以一种简单的方式显示了这个问题

我需要在函数1()中调用函数2(),其中T:class,new(),其中T:class

Something<T> function1<T>() where T : class {
  //cannot call function2 directly due to compile error
  //return function2<T>();

  //What I need as a pseudo code
  if (T is TheClass and T is new())
    return Then function2<T>()
  else
    throw Exception
} 

Something<T> function2<T>() where T : TheClass, new() {
  //...
} 
Something function1(),其中T:class{
//由于编译错误,无法直接调用function2
//返回函数2();
//我需要的是伪代码
if(T是类,T是新的()
然后返回函数2()
其他的
抛出异常
} 
Something function 2(),其中T:TheClass,new(){
//...
} 
new()
限制在运行时无法验证(与继承不同,继承可以使用
,因为
/
)-因此没有C结构可以编写来从
函数1
调用
函数2
,并保持其强类型


您唯一的选择是通过反射构造方法,然后调用它。看

你真的不能那样做。我猜
function2
在某个时候正在执行
newt()
,而这对于
T:class
约束在
function1
中是不可能的

例如,您可以尝试删除
new()
约束,并使用对
ConstructorInfo
的检查手动执行该约束,并从中获取一个实例:

   Type type = typeof(T);
   ConstructorInfo ctor = type.GetConstructor(new Type[0]);
   if(ctor == null) throw new InvalidOperationException();
   object instance = ctor.Invoke(new object[0]);

既然输入无效时仍会引发异常,为什么不应用相同的限制(类,new())对于function1?您在尝试直接调用function2时遇到了什么编译器错误?对于什么类型的T?@MarcoFatica无论
T
是什么都不重要,因为
function1
上的约束并不强制它具有默认构造函数,它不能用于
function2
的参数。因为您需要不同的逻辑根据
T
的内容,您将不得不求助于反射,或者对新的able类型使用一种方法,对其他类型使用另一种方法。