简体   繁体   English

接受继承类型的C#泛型类。

[英]C# generic class accepting a inherited type.

**Preface I'm very new to generics. **序言我对泛型非常陌生。 I have a class I created called Geno. 我创建了一个名为Geno的课程。 My Peno class simply contains a string Name property. 我的Peno类仅包含一个字符串Name属性。 I'm wondering why I cannot call T.Name from within a method on this class. 我想知道为什么我不能从此类的方法中调用T.Name。 How would I access the properties on T? 我将如何访问T上的属性? Any good resources on how this works? 有什么好的资源如何运作?

public class Geno<T> where T : Peno
{

}

public string GetName()
{
   return T.Name;
}

Is your Name property an instance property or a static property? 您的Name属性是实例属性还是静态属性? If it's a static property, you don't get polymorphism anyway - you could just call Peno.Name . 如果它是静态属性,那么无论如何您都不会获得多态性-您可以调用Peno.Name

If it's an instance property, you need an instance on which to call it. 如果它是实例属性,则需要在其上调用它的实例。 For example: 例如:

public class Geno<T> where T : Peno
{
    private readonly T value;

    public Geno(T value)
    {
        this.value = value;
    }

    public string GetName()
    {
       return value.Name;
    }    
}

If this doesn't help, please give a more complete example of what you're trying to do. 如果这样做没有帮助,请提供您要尝试执行的操作的更完整示例。

T is the type Peno . TPeno类型。 So what you try to do is Peno.Name , which is probably not what you want. 因此,您尝试做的是Peno.Name ,这可能不是您想要的。 Something like this would work: 这样的事情会起作用:

public string GetName(T t)
{
    return t.Name;
}

Static properties does not support inheritence. 静态属性不支持继承。 Hence you can just call Peno.Name rather than going for T. 因此,您可以只调用Peno.Name而不是T。

If in your case you want to access a normal property, you need to create an instance of T which will let you call its property Name. 如果您要访问常规属性,则需要创建T的实例,该实例将让您将其称为Name。

T is a Generic Type Parameter, not a parameter being passed into the class that is using T. T是泛型类型参数,不是传递给使用T的类的参数。

A Good example of this is List<T> you say this is a List, which means you are creating a list that contains object of the type of String. 一个很好的例子是List<T>您说这是一个列表,这意味着您正在创建一个包含String类型对象的列表。

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

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