Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/261.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/4/oop/2.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#_Oop - Fatal编程技术网

C# 没有泛型的参数约束

C# 没有泛型的参数约束,c#,oop,C#,Oop,给出下面的例子 public class Example { public static T GetDefaultValue<T>() { // return ??? } } 公共类示例 { 公共静态T GetDefaultValue() { //返回??? } } 如果不使用泛型,我可以使用什么方法将传递给GetDefaultValue函数的类型约束为具有实现IDisposable的无参数构造函数的类? 如何实例化该类型的实例以从GetDefau

给出下面的例子

public class Example
{
    public static T GetDefaultValue<T>()
    {
    // return ???
    }
}
公共类示例
{
公共静态T GetDefaultValue()
{
//返回???
}
}
如果不使用泛型,我可以使用什么方法将传递给GetDefaultValue函数的类型约束为具有实现IDisposable的无参数构造函数的类?
如何实例化该类型的实例以从GetDefaultValue函数返回?

我对您的意思感到困惑。。但是您可以将类型约束到接口,而不是使用泛型(没有泛型?)

public ISomeInterface GetDefaultValue(ISomeInterface theObject)
{
  ...
}

使用泛型,您可以

public static T GetDefaultValue<T>() where T : new(), IDisposable
{
   return new T();
}
public static T GetDefaultValue(),其中T:new(),IDisposable
{
返回新的T();
}
但是,无论您将
T
设置为什么类型,都必须有一个默认构造函数。这样,调用
GetDefaultValue()
将获得所需的精确类型,而无需强制转换,因为
GetDefaultValue()
返回了一个
IDisposable


我假设您不想要泛型解决方案,因为实例化泛型类型的能力并不广为人知。我个人偶然发现了这个,天哪,这是一个救命恩人

我不明白,您的示例类具有泛型
t