c# - 泛型允许按类型对哪些元素进行参数化?

标签 c# generics

这是一些测试的问题。问题是“泛型允许按类型参数化哪些元素?” 以及 5 种答案:

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

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

  1. 类(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));
        }
    }
}

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

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.

我在这个地方问自己 - “按类型参数化”到底意味着什么?上面的属性是否按类型参数化? 正确答案是什么:

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

  1. true
  2. true
  3. true
  4. true
  5. 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/

相关文章:

c# - 更快地查明用户是否存在于系统中的方法?

Java 泛型转换为通配符规则

generics - 关于 Rust 中的泛型和特征的问题

c# - 在 List<Parent> 对象的泛型函数中使用子类型

java - 将通用列表转换为数组

generics - 提取切片-99个问题#18( Kotlin )

c# - 如何处理相等比较中的空值?

c# - 如何在没有数据库的情况下生成仅用于显示用户在 c# 表单应用程序中填写的表单数据的 Crystal 报表

C# Environment.GetEnvironmentVariable(...) 不适用于 OSX

c# - 使用 C# 将 HashSet 中的一组正则表达式与 ASP.NET 中的字符串进行匹配的最佳方法是什么?