我想创建一个接受值类型和引用类型参数的简单方法,即int是值,string是引用。
所以这就是我的开始:
public bool AreBothNotNull<T>(T? p1, T? p2)
{
return (p1.HasValue && p2.HasValue);
}
所以我希望能够像这样使用它:
var r1 = AreBothNotNull<int>(3, 4); // will be true
var r2 = AreBothNotNull<int>(3, null); // will be false
var r3 = AreBothNotNull<string>("three", "four"); // will be true
var r4 = AreBothNotNull<string>(null, "four"); // will be false
但是我遇到的第一个问题是
The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'System.Nullable'
为了继续,我向我的方法添加了一个结构约束
public bool AreBothNotNull<T>(T? p1, T? p2) where T : struct
但是现在该方法不接受基于字符串的调用,并给我这个错误:
The type 'string' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method.
这可能吗?或者为什么我们不能这样做?
最佳答案
您的问题是您想要相互冲突的泛型类型约束:
-
Nullable<T>
仅适用于值类型 - 引用类型不是值类型
因此您需要有两个重载才能使您的代码正常工作:
public static bool AreBothNotNull<T>(T? p1, T? p2) where T : struct
{
return (p1.HasValue && p2.HasValue);
}
public static bool AreBothNotNull<T>(T p1, T p2)
{
return (p1 != null && p2 != null);
}
仍然,以下行永远不会编译:
var r3 = AreBothNotNull<string>(3, 4);
这里有冲突,泛型类型参数声明参数的类型是string
, 但代码试图通过 int
s 代替。
关于c# - 是否可以创建接受(可空)值类型和引用类型的 C# 泛型方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4003026/