Hei*_*bug 8 c# generics mono null nullable
假设我有以下课程:
public class GenericClass<T>
{
public T Find()
{
//return T if found otherwise null or Nullable<T>
}
}
Run Code Online (Sandbox Code Playgroud)
在某个地方,我想把我的班级专门T
用于a class
,其他时候用a struct
.我正面临这个问题:我不能返回一个Nullable<T>
if T
类型不限于一个struct
.
我想提供一个我的Find
方法的实现,如果T
专门用于a class
或a struct
.如果Find
失败,我想返回,null
否则T
是一个类Nullable<T>
.
没有使用反射可能吗?如果有,怎么样?
Ree*_*sey 16
You can return default(T)
.
For a class, this will be null
. For any Nullable<T>
, this will be a Nullable<T>
without a value (effectively null
).
That being said, if you use this with a struct
and not a Nullable<T>
as the type, default(T)
will be the default value of the struct.
如果你想为任何类或结构统一工作,你可能需要返回两个值 - 你可以在这里使用框架作为灵感,并使用TryXXX方法,即:
public bool TryFind(out T)
Run Code Online (Sandbox Code Playgroud)
然后,您可以default(T)
在找不到值时使用,并返回false.这避免了对可空类型的需求.Tuple<bool, T>
如果你想避免out参数,你也可以写这个返回a 或类似的,即:
public Tuple<bool, T> Find()
Run Code Online (Sandbox Code Playgroud)
最后一个选项可能是使您的类非泛型,然后使用一对泛型方法:
class YourClass // Non generic
{
public T FindReference<T>() where T : class
{
// ...
return null;
}
public Nullable<T> FindValue<T>() where T : struct
{
// ...
return default(T);
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,您需要不同的名称,因为您不能完全基于返回类型重载方法.
归档时间: |
|
查看次数: |
6197 次 |
最近记录: |