通过 base-class 的实例分配给派生 class 的成员的较短版本

Shorter version of assigning to a member of a derived class by an instance of a base-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 条件中有很多这样的代码。是否有此的 shorthand 版本,所以我不必创建临时派生变量?

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

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

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

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

为了合规性,这是 veriant OP 选择的:

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

作业

baseVar = derivedVar;

是多余的所以你可以做

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