泛型允许哪些元素按类型参数化?

Of which elements does Generics allow parameterization by type?

这是一些测试的问题。问题是 "Of which elements does Generics allow parameterization by type?" 和 5 个答案变体:

  1. Classes
  2. Structs
  3. Methods
  4. Events
  5. Fields

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

  1. 类.

我们可以这样写

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

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

关于方法。我们可以这样写:

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

我看到以下答案:

Properties, events, constructors etc can't be generic - only methods and types can be generic. Most of the time that's not a problem, but I agree that sometimes it's a pain. Brannon's answer gives two reasonable workarounds.

我在这个地方问自己- "parameterization by type" 下到底是什么意思? 属性 以上是否按类型参数化? 正确答案是什么:

  1. true
  2. true
  3. true
  4. false
  5. false

  1. true
  2. true
  3. true
  4. true
  5. true

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

Property is parametrized by type, correct (the same with Events)?

不,不是。 属性 本身没有类型参数 - 你在 class.

上得到了它

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

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

...

会更清楚
class NonGenericType
{
    void GenericMethod<T>() { }
}

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

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

通用的 属性 必须类似于:

// 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>;