gpt4 book ai didi

c# - 为什么使用 as 关键字初始化对象

转载 作者:太空狗 更新时间:2023-10-30 01:05:34 25 4
gpt4 key购买 nike

我刚刚遇到了一些我不理解的代码。这是有效的

Class c = new BaseClass() as Class;

我不明白这样做的好处,所以我创建了自己的控制台应用程序以查看它的作用。

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; }
}
}

我只能假设这提供了一些与多态相关的额外帮助,但我无法弄清楚如何或看到两者之间的任何区别:

BaseDemo baseDemo2 = new Demo();  

BaseDemo baseDemo3 = new Demo() as BaseDemo;

最佳答案

这个

Class c = new BaseClass() as Class;

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

Class c = new BaseClass()

够了……单一异常:

var c = new BaseClass() as Class;

现在 c 是类型 Class 的引用(但引用 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 中所写:

The as operator is like a cast operation. However, if the conversion isn't possible, as returns null instead of raising an exception.

Note that the as operator performs only reference conversions, nullable conversions, and boxing conversions. The as operator can't perform other conversions, such as user-defined conversions, which should instead be performed by using cast expressions.

关于c# - 为什么使用 as 关键字初始化对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18358203/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com