简体   繁体   English

c# 如何在获取属性中使用模板?

[英]c# how to use a template in a get property?

I have some problem to use a template in a get property in c#.我在 c# 的 get 属性中使用模板时遇到了一些问题。 The following class has no problem:下面的class没有问题:

public class test
{
    public T GetDefault<T>()
    {
        return default(T);
    }
}

But i would like to use get property and then there is a error但我想使用 get 属性然后出现错误

unexpected use of generic name意外使用通用名称

the code is following:代码如下:

public class test
{
    public T Default<T> => default<T>;
}

There are no generic properties in C# so far.到目前为止,C# 中没有通用属性。 You can find details here and here :您可以在此处此处找到详细信息:

We must reserve space for the backing store for the generic property [...].我们必须为通用属性的后备存储保留空间 [...]。 But we don't know how much to reserve.但我们不知道要预留多少。 Even if the compiler had read and understood every possible use of the generic.即使编译器已经阅读并理解了泛型的所有可能用法。

MSDN states here : MSDN 在这里声明:

Properties are a natural extension of fields.属性是字段的自然扩展。 Both are named members with associated types.两者都是具有关联类型的命名成员。

They must have an associated type at compile-time.它们必须在编译时具有关联的类型。

I don't think current C# version support such syntax sugar.我认为当前的 C# 版本不支持这种语法糖。 But you can get similar behavior like this:但是你可以得到类似这样的行为:

public static class test<T>
{
    public static T Default => default(T);
}

And then use it:然后使用它:

var value = test<int>.Default;

Actually, if you strugling between two, I would reccomend to stay at methods:实际上,如果您在两者之间挣扎,我建议您使用以下方法:

public static class test
{
    public static T GetDefault<T>() => default(T);
}

Benefit is that you can put different extensions in same test class, on different types.好处是您可以在不同类型的同一测试 class 中放置不同的扩展。

if you want to make it generic the generic type should be passed to the class as following如果您想使其通用,则应将通用类型传递给 class,如下所示

public class test<T>{
    public T Default => default(T);
}

Calling it调用它

var defaultValue = new test<TheType>.Default;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM