由基类实例分配给派生类成员的较短版本

时间:2016-08-03 12:08:42

标签: c# inheritance casting derived-class

考虑这个小例子:

public class BaseClass { }
public class DerivedClass : BaseClass { public int Field; }

public static class Program
{
    public static void Main( string[] args)
    {
        BaseClass baseVar = new DerivedClass();

        if( baseVar is DerivedClass )
        {
            var derivedVar = (DerivedClass)baseVar;

            derivedVar.Field = 1;

            baseVar = derivedVar;
        }
    }
}

我在if-conditions中有很多这样的代码。有没有这个的简写版本,所以我不必创建临时派生变量?

2 个答案:

答案 0 :(得分:3)

一种方法是安全的类型转换:

BaseClass base = new DerivedClass();
DerivedClass derived = base as DerivedClass;
derived?.Field = 1;

注意:as是安全转换 - 将转换为null或返回null。 ?是C#6功能,当变量不是nullPtr时,方法或赋值正在执行。您不必编写baseVar = derivedVar,因为两者都是通过引用绑定的。当您转换并更改字段时,引用根本没有更改。

此外,这里有一篇关于C#6.0 https://msdn.microsoft.com/de-de/magazine/dn802602.aspx中的空传播的MSDN文章

为了遵守规定,正确的OP选择了:

BaseClass base = new DerivedClass();
(base as DerivedClass)?.Field = 1;

答案 1 :(得分:1)

作业

baseVar = derivedVar;

是多余的,所以你可以做到

if( baseVar is DerivedClass ) {
    ((DerivedClass)baseVar).Field = 1;
}