我想创建将某些类型的值作为参数的泛型函数。
MyGenericClass<T>(parameter)
(参数也可以由属性设置,因此无需在此处使用构造函数)MyGenericClass<NotNullType(T)>(parameter.Value)
example的内容:对于参数int?x,函数应该返回MyGenericClass<int>(x.Value)
。这是我为执行此操作而编写的代码,但没有成功:
private MyGenericClass GetMyGenericClassOrNull<T> (T value) {
if (value != null) {
var underlyingType = Nullable.GetUnderlyingType(typeof(T));
if (underlyingType == null) {
return new MyGenericClass<T>(value);
} else {
return new MyGenericClass<underlyingType>(value);
}
}
return null;
}
如您所料,line:return new MyGenericClass<underlyingType>(value);
在这里是有问题的。
有什么办法做这种事吗?
您可以尝试:
public class MyGenericClass
{
}
public class MyGenericClass<T> : MyGenericClass
{
public MyGenericClass(T value)
{
}
}
public static MyGenericClass GetMyGenericClassOrNull<T>(T? value) where T : struct
{
if (value != null)
{
return new MyGenericClass<T>(value.Value);
}
return null;
}
public static MyGenericClass GetMyGenericClassOrNull<T>(T value)
{
if (value != null)
{
return new MyGenericClass<T>(value);
}
return null;
}
您有两种单独的方法。可空类型将转到第一个,即T
不可空“基”类型。
请注意,public static MyGenericClass<T>
如果需要,您可以进行签名而不会出现任何问题。目前尚不清楚您MyGenericClass
的建造方式。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句