C#:如何以及如何不初始化一个对象?
C#: how to and how not to initialize an object?
这个问题比通常的堆栈溢出问题更具理论性。
我的问题是:如果 class A 继承自 class B 如果它们都具有空构造函数(无参数),那么 is/are 初始化对象的正确方法是什么?
这是选项:
- A a = new B();
- B b = 新 A();
- A a = new B() as A;
- B b = new A() as B;
我认为 1 和 3 都有可能,但我真的不确定。
谁能解释一下哪些是对的,为什么?
简答:视情况而定。
如果您想要 A
类型的对象,请使用构造函数 A()
。如果你想要一个 B
类型的对象,那么使用构造函数 B()
.
为了使事情更具体,动物 classes.
public class Giraffe : Animal {}
public class Animal {}
那么你的代码就变成了
Animal a = new Giraffe(); // perfectly normal, imo
//Giraffe b = new Animal(); compiler error!
Animal a = new Giraffe() as Animal; // "as Animal" is redundant
Giraffe b = new Animal() as Giraffe; // this is strange, but compiler is OK with it... not sure of a use case for this exact piece of code.
变量的类型并没有那么重要,除非您在 class 上公开一个字段或 属性。在这种情况下,请考虑该对象在外人看来如何。如果你想让外界将你 field/property 视为类型 Animal
的对象,请使用它。与 Giraffe
.
类型相同
这个问题比通常的堆栈溢出问题更具理论性。 我的问题是:如果 class A 继承自 class B 如果它们都具有空构造函数(无参数),那么 is/are 初始化对象的正确方法是什么?
这是选项:
- A a = new B();
- B b = 新 A();
- A a = new B() as A;
- B b = new A() as B;
我认为 1 和 3 都有可能,但我真的不确定。 谁能解释一下哪些是对的,为什么?
简答:视情况而定。
如果您想要 A
类型的对象,请使用构造函数 A()
。如果你想要一个 B
类型的对象,那么使用构造函数 B()
.
为了使事情更具体,动物 classes.
public class Giraffe : Animal {}
public class Animal {}
那么你的代码就变成了
Animal a = new Giraffe(); // perfectly normal, imo
//Giraffe b = new Animal(); compiler error!
Animal a = new Giraffe() as Animal; // "as Animal" is redundant
Giraffe b = new Animal() as Giraffe; // this is strange, but compiler is OK with it... not sure of a use case for this exact piece of code.
变量的类型并没有那么重要,除非您在 class 上公开一个字段或 属性。在这种情况下,请考虑该对象在外人看来如何。如果你想让外界将你 field/property 视为类型 Animal
的对象,请使用它。与 Giraffe
.