4

I've just run across some code I don't understand. It is effectively

Class c = new BaseClass() as Class;

I don't understand the advantage of doing this, so I created my own console application to see what it does.

namespace Initialize
{
    class Program
    {
        static void Main(string[] args)
        {
            Demo demo = new Demo();
            demo.BaseProp = "";
            demo.DemoProp = "";

            BaseDemo baseDemo = new BaseDemo();
            baseDemo.BaseProp = "";

            BaseDemo baseDemo2 = new Demo();
            baseDemo2.BaseProp = "";

            BaseDemo baseDemo3 = new Demo() as BaseDemo;
            baseDemo3.BaseProp = "";

            //fails runtime
            //Demo demo2 = (Demo)baseDemo;

            Demo demo3 = (Demo)baseDemo2;
            demo3.BaseProp = "";
            demo3.DemoProp = "";

            Demo demo4 = (Demo)baseDemo3;
            demo4.BaseProp = "";
            demo4.DemoProp = "";
        }
    }

    class BaseDemo
    {
        public string BaseProp { get; set; }
    }

    class Demo : BaseDemo
    {
        public string DemoProp { get; set; }
    }
}

I can only assume this offers some additional help in relation to polymorphous but I can't work out how or see any difference between:

BaseDemo baseDemo2 = new Demo();  

and

BaseDemo baseDemo3 = new Demo() as BaseDemo;
4

4 回答 4

4

这个

Class c = new BaseClass() as Class;

完全没用。如果Class是 的基类,BaseClass则强制转换是自动的,否则强制转换将始终返回null

Class c = new BaseClass()

已经足够了......单个例外:

var c = new BaseClass() as Class;

nowc是类型的引用Class(但引用 a BaseClass)。您正在强制隐式类型变量的类型(非常没用......您可以直接编写Class c = new BaseClass();

请注意,as与强制转换运算符相反,关键字()不会“激活”两个类之一可能已经实现的implicit/强制转换运算符。explicit

这不会编译:

class BaseClass
{
    public static implicit operator Class(BaseClass b)
    {
        return new Class();
    }
}

class Class
{            
}

Class c = new BaseClass() as Class;

正如msdn中所写:

as 运算符类似于强制转换操作。但是,如果无法进行转换,则 as 返回 null 而不是引发异常。

请注意,as 运算符仅执行引用转换、可为空的转换和装箱转换。as 运算符不能执行其他转换,例如用户定义的转换,而应使用强制转换表达式来执行。

于 2013-08-21T13:07:44.477 回答
1

你是对的,在你的情况下没有区别。通过使用as,您只是在陈述一个明显的事实,即Demo实例也是BaseDemo.

as关键字在其他上下文中很有用,尤其是当您想要测试对象是否属于某种类型并在转换成功时使用它时。

于 2013-08-21T13:09:34.997 回答
0

如果投射失败,则投射返回asnull这是一种转换和检查 anull而不是抛出异常的安全方法。

我正在努力思考为什么你的例子会被使用..

于 2013-08-21T13:05:04.953 回答
0
BaseDemo baseDemo2 = new Demo();  
BaseDemo baseDemo3 = new Demo() as BaseDemo;

绝对没有区别,就像和之间没有区别if (condition == true)一样if (condition)

ADemo aBaseDemo所以as在这种情况下安全强制转换 ( ) 是多余的。

另一方面:

Class c = new BaseClass() as Class;

Class 延长 BaseClass演员阵容将失败,使c null.

于 2013-08-21T13:06:34.400 回答