小编jws*_*305的帖子

为什么不使用C#8编译“ where T:object”的类型约束

根据https://github.com/dotnet/csharplang/blob/master/proposals/csharp-8.0/nullable-reference-types-specification.md object,现在是有效的类型约束。

可空的引用类型可用作通用约束。此外,对象现在作为显式约束有效。现在没有约束就等于对象?约束(而不是对象),但是(不同于之前的对象)对象?不被禁止作为显式约束。

我认为应该可以正确编译,但是Visual Studio不会让我编译它。

public class A<T> where T : object { }
Run Code Online (Sandbox Code Playgroud)

我是看错了这还是VS或C#8问题?

更新

我正在尝试为缓存定义接口。

public interface IDataCache
{
    void Put<T>(string key, T value) where T : notnull;
    T? Get<T>(string key) where T : notnull;
}
Run Code Online (Sandbox Code Playgroud)

理想情况下,我不希望将null值缓存,但是我也不能保证将值保留在缓存中。有时我想缓存一个类,但有时它可能是整数。这是否有可能实现,或者我必须针对每种情况制定单独的方法?

public interface IDataCache
{
    void Put<T>(string key, T value) where T : notnull;

    // This seems really nasty!
    T? GetClass<T>(string key) where T : class;
    T? GetStruct<T>(string key) where T : struct;
}
Run Code Online (Sandbox Code Playgroud)

c# visual-studio c#-8.0 nullable-reference-types

1
推荐指数
1
解决办法
179
查看次数