这是一些测试的问题。问题是“泛型允许按类型参数化哪些元素?” 以及 5 种答案:
- Classes
- Structs
- Methods
- Events
- Fields
乍一看问题很简单,但我不确定正确答案。让我们一步一步来。
- 类(class)。
我们可以写一些类似的东西
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));
}
}
}
属性是按类型参数化的,正确吗(与事件相同)?但在下一页
我看到以下答案:
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.
我在这个地方问自己 - “按类型参数化”到底意味着什么?上面的属性是否按类型参数化? 正确答案是什么:
- true
- true
- true
- false
- false
或
- true
- true
- true
- true
- true
最佳答案
Property is parametrized by type, correct (the same with Events)?
不,不是。属性本身没有类型参数 - 您已经在类中获得了它。
将其与您的方法示例进行比较:
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>;
关于c# - 泛型允许按类型对哪些元素进行参数化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28743673/