【问题标题】:Why can't we set a derived type for generic parameters?为什么我们不能为泛型参数设置派生类型?
【发布时间】:2020-05-08 10:12:48
【问题描述】:

在下面的代码中

    public class CustomValidator<T>
    {
        // some code 
    }

    public abstract class Parent
    {
        public CustomValidator<Parent> Validator { get; protected set; }
    }

    public class Child : Parent
    {
        public string Name { get; set; }
        public Child()
        {
            Validator = new CustomValidator<Child>();
            // Doesn't work, cannot cast implicitly 
        }
    }

由于我们可以将孩子分配给父母, 为什么我们不能为CustomValidator&lt;Parent&gt; 类型的属性设置CustomValidator&lt;Child&gt;?

【问题讨论】:

  • 因为并非所有从 Parent 派生的类都将是 Child 类型,这意味着其他代码可能会向此验证器添加其他东西,从 Parent 派生,而不是 Child。

标签: c# .net generics


【解决方案1】:

如果您的代码允许,您可以尝试利用 covariance in C# 引入协变接口:

public interface ICustomValidator<out T> // Your new interface
{
    // some code 
}

public class CustomValidator< T>:ICustomValidator<T>
{
    // some code 
}

public abstract class Parent
{
    // Change property to your new interface
    public ICustomValidator<Parent> Validator { get; protected set; }
}

public class Child : Parent
{
    public string Name { get; set; }
    public Child()
    {
        Validator = new CustomValidator<Child>();
    }
}

如果你不能使你的ICustomValidator 接口(通过用out 关键字标记泛型参数)协变然后@Michael Randall 在cmets 中说 CustomValidator&lt;Parent&gt; != CustomValidator&lt;Child&gt;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-26
    • 1970-01-01
    • 2011-10-09
    • 1970-01-01
    • 2010-12-22
    相关资源
    最近更新 更多