Generics允许哪些元素按类型进行参数化?

时间:2015-02-26 13:24:04

标签: c# generics

这是一些测试中的问题。问题是“泛型允许按类型参数化的哪些元素?” 和5个答案变体:

  
      
  1.   
  2. 的Structs
  3.   
  4. 方法
  5.   
  6. 活动
  7.   
  8. 字段
  9.   

乍一看问题很简单,但我不确定答案是否正确。让我们一步一步。

  1. 类。
  2. 我们可以写类似

    的内容
    class SuperKeyType<K, V, U>
        where U : System.IComparable<U>
        where V : new()
    { }
    

    所以,类可以按类型参数化。与Structs相同。

    关于方法。我们可以写下以下内容:

    class GenericList<T>
    {
        // CS0693 
        void SampleMethod<T>() { }
    }
    

    所以,方法也是。

    关于活动和领域:

    class Foo<TValue> {
        public string Value { get; set; }
        public TValue TypedValue {
            get {
                return (TValue)Convert.ChangeType(Value, tyepof(TValue));
            }
        }
    }
    

    属性按类型进行参数化,正确(与事件相同)?但在下一页

    Making a generic property

    我看到以下答案:

      

    属性,事件,构造函数等不能是通用的 - 只有方法   和类型可以是通用的。大多数时候这不是问题,但我   同意有时这是一种痛苦。布兰农的回答有两个   合理的解决方法。

    我这个地方我问自己 - 什么意思在“按类型参数化”下呢?以上属性是否按类型参数化? 什么是正确的答案:

      
        
    1.   
    2.   
    3.   
    4.   
    5.   

      
        
    1.   
    2.   
    3.   
    4.   
    5.   

2 个答案:

答案 0 :(得分:2)

类,结构和方法。使用参数化类型作为属性类型的事实并不意味着属性本身是参数化的。类型的类是。

答案 1 :(得分:2)

  

属性是按类型参数化的,正确的(与事件相同)?

不,不是。该属性本身没有类型参数 - 您已经在上获得了它。

将其与您的方法示例进行比较:

class GenericList<T>
{
    // CS0693 
    void SampleMethod<T>() { }
}

......哪个更清楚

class NonGenericType
{
    void GenericMethod<T>() { }
}

注意类型参数(T)是如何在类签名方法签名中引入的,不是

您不能为字段,属性,事件,构造函数或终结器指定类型参数。

通用属性必须类似于:

// Not valid: properties can't be generic. But imagine...    
public T Value<T> { get; set; }

同样,通用构造函数也可能是:

public class Foo
{
    // Not valid: constructors can't be generic. But imagine...
    public Foo<T>(T initializationValue)
    {
        // Note that this isn't constructing a Foo<T> -
        // Foo is a non-generic type. It's only the constructor
        // that is generic.
    }
}

通用字段甚至更奇怪。它可能意味着什么?

private int field<T>;
...
int x = field<string>;