简体   繁体   English

将实例方法的参数限制为实例的类型

[英]Restrict instance method's parameter to instance's type

Say I have an abstract base class BaseClass . 假设我有一个抽象基类BaseClass

I'd like to give it a method that looks something like the following 我想给它一个类似于下面的方法

public void CopyPropertiesFrom<T>(T source) where T == ThisDerivedClass : BaseClass
{
     // ...
}

I want the method to be generic, but to be restricted to the most derived class of the current instance. 我希望该方法是通用的,但要限制为当前实例的派生类最多。 (My method will use reflection, so I don't actually need to override CopyPropertiesFrom in any child classes, but I would still like the compile-time type safety.) (我的方法将使用反射,所以我实际上不需要在任何子类中重写CopyPropertiesFrom ,但我仍然希望编译时类型安全。)

Is there any way to express this in valid C#? 有没有办法在有效的C#中表达这个?

No, there isn't. 不,没有。 You can only allow a class and any derived (irrelevant the depth of inheritance). 您只能允许一个类和任何派生的(与继承的深度无关)。

Not only is there no way of expressing this, but it would be impossible for the compiler to enforce anyway. 不仅无法表达这一点,而且无论如何编译器都无法执行。 The point of generics is that they can be checked at compile time. 泛型的关键是它们可以在编译时检查。 What would you expect this to do... 你期望这样做......

BaseClass foo = new DerivedClass();
foo.CopyPropertiesFrom<BaseClass>(new OtherDerivedClass());

The compiler only knows about foo as BaseClass - how should it know to complain that actually , you should be calling foo.CopyPropertiesFrom<DerivedClass> ? 编译器只知道fooBaseClass - 如何知道抱怨实际上 ,你应该调用foo.CopyPropertiesFrom<DerivedClass>

You can check within the method, of course - but I'm not sure I'd even make it generic: 当然,您可以在方法中进行检查 - 但我不确定我是否会将其设为通用的:

public void CopyPropertiesFrom(BaseClass other)
{
    if (other.GetClass() != GetClass())
    {
        throw new ArgumentException("...");
    }
}

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

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