gpt4 book ai didi

C# 字符串的类型?是 TypeKind.Class

转载 作者:行者123 更新时间:2023-12-02 18:45:53 24 4
gpt4 key购买 nike

重新表述问题:我有一个等式比较器,其通用类型约束为 class

public class ReferenceEqualityComparer<T> : IEqualityComparer<T> where T : class
{
public static ReferenceEqualityComparer<T> Default => new();

public bool Equals(T? x, T? y) => ReferenceEquals(x, y);

public int GetHashCode(T? obj) => RuntimeHelpers.GetHashCode(obj);
}

上课时我们说

public class A
{
public string? P1{get; set;}
}

由代码生成器使用

[Generator]
public class MyCodeGenerator : ISourceGenerator
{
}

NetAnalyzer 表示 string? 有一个 TypeKind 类

但是当我这样做时,

#nullable enable        
[TestMethod]
public void RefTest()
{
string? s1 = "adsad";
string? s3 = s1;
Assert.IsTrue(ReferenceEqualityComparer<string?>.Default.Equals(s1, s3));
}
#nullable restore

它说string?与“class”约束不匹配。即使分析器告诉我它是一个类,我是否在这里遗漏了一些东西?或者我误解了这个概念?

原问题:根据Nullable的描述从 Microsoft 文档来看,它们被归类为 structs,但为什么 CodeAnalyzer 告诉我 string 的 TypeKind? 是 TypeKind.Class?

这里有一些上下文,在我正在编写的库中,对源生成(C# 9 源生成器)的类进行了分析,这本质上是使用 .NetAnalyzer。将检查类的每个属性是否将其类型视为类。事实证明 string? 被视为一个类。

最佳答案

There is C# 中可空类的特定约束,因此从编译时约束的角度来看,SomeRefType?T:class 不匹配,但会匹配 T:class? .

where T : class The type argument must be a reference type. This constraint applies also to any class, interface, delegate, or array type. In a nullable context in C# 8.0 or later, T must be a non-nullable reference type.

where T : class? The type argument must be a reference type, either nullable or non-nullable. This constraint applies also to any class, interface, delegate, or array type.

因此,在可为 null 的上下文中,您可能需要使用第二个:

public class ReferenceEqualityComparer<T> : IEqualityComparer<T> where T : class?

这不会对 string?string 发出任何警告。

关于C# 字符串的类型?是 TypeKind.Class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67439154/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com