c# - 是否可以创建接受(可空)值类型和引用类型的 C# 泛型方法?

标签 c# .net generics value-type reference-type

我想创建一个接受值类型引用类型参数的简单方法,即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/

相关文章:

java - Google guava iterables.filter,与泛型相关的类型错误?

c# - ASP.NET Core - 无法在属性 '1' 上设置类型 'System.Int32' 的默认值 'MerchantStatus'

c# - 数据表的实体列表

c# - TextBox 控件使用什么事件来在按下 enter 时发出文本更改信号?

c# - 是否有基于 .NET 的 CSS 抽象库?

c# - 从资源读取文件时指定编码

c# - 当类型参数未知时如何调用泛型类型实例的方法?

c# - 如何从 C# 中的封闭构造类中获取基类对象

c# - IComparable<T> 作为逆变的好处?

c# - NativeWindow的AssignHandle没有父窗体