简体   繁体   English

C# 中的通用类型约束

[英]Generic type constraint in C#

I was going through the MSDN document for the Generic type constraint and I found the following paragraph.我正在浏览通用类型约束的 MSDN 文档,我发现了以下段落。

You use the default constraint to specify that your derived class overrides the method without the constraint in your derived class, or explicit interface implementation.您使用默认约束来指定您的派生 class 覆盖派生 class 中没有约束的方法,或显式接口实现。 It's only valid on methods that override base methods, or explicit interface implementations:它仅对覆盖基方法或显式接口实现的方法有效:

public class D : B
{
    // Without the "default" constraint, the compiler tries to override the first method in B
    public override void M<T>(T? item) where T : default { }
}

I couldnt understand the part of derived class overriding the method without the constraint.我无法理解派生 class 在没有约束的情况下覆盖方法的部分。 Can this please be explained with an elaborated example with the value needs to be passed for T in "M" method?请用一个详细的例子来解释这个问题,在“M”方法中需要为 T 传递值?

It might be easier to understand if you try to do it.如果您尝试这样做,可能会更容易理解。 Let's say you have:假设您有:

public abstract class BaseLogger
{
    public void Log<T>(T? item) where T : struct 
    { 
        Console.WriteLine("I **cannot** be overriden!"); 
    }

    public virtual void Log<T>(T? item) 
    {
        Console.WriteLine("I **can** be overriden!"); 
    }
}

Now, you have a child class, where you want to override the only virtual method:现在,你有一个孩子 class,你想覆盖唯一的虚拟方法:

public class Logger : BaseLogger
{
    public override void Log<T>(T? item) 
    {
        Console.WriteLine("I am overwriting my parent method!"); 
    }
}

All good, right?一切都好,对吧? Well, not exactly, no:好吧,不完全是,不:

Compilation error: 'Logger.Log<T>(T?)': cannot override inherited member 'BaseLogger.Log<T>(T?)' because it is not marked virtual, abstract, or override
Compilation error: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>'

As the document explains, the compiler cannot resolve the ambiguity between T?正如文档所解释的那样,编译器无法解决T? (a nullable reference type) and T? (可空引用类型)和T? (the shorthand for Nullable<T> ), so you need a way to specify the method that can be overriden. Nullable<T>的简写),因此您需要一种方法来指定可以重写的方法。 That's where the new default constraint becomes useful:这就是新的default约束变得有用的地方:

public class Logger : BaseLogger
{
    public override void Log<T>(T? item) where T: default
    {
        Console.WriteLine("I am overwriting my parent method!"); 
    }
}

Now it actually compiles.现在它实际上编译了。 See it live: https://do.netfiddle.net/vXgzWx现场观看:https://do.netfiddle.net/vXgzWx

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

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