'objMyClass'是一个'字段'但是像'类型'一样使用 [英] 'objMyClass' is a 'field' but is used like a 'type'
本文介绍了'objMyClass'是一个'字段'但是像'类型'一样使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
代码示例:
Code Sample:
class MyBaseClass
{
class MyNestedClass
{
String _MyVariable;
public String MyVariable
{
get { return _MyVariable; }
set { _MyVariable = value; }
}
}
//This one valid
void MyMethod()
{
MyNestedClass objMyClass = new MyNestedClass();
objMyClass.MyVariable = "";
}
//This also valid
MyNestedClass objMyClass = new MyNestedClass() { MyVariable = "Some Value" };
//Everyone know, The Below commented code raise the following error, when it will be uncommented.
//Invalid token 'void' in class, struct, or interface member declaration
//objMyClass.MyVariable = "Some Value";
}
在方法之外没有任何对象(objMyClass)的使用,在这个示例中对象初始化器有什么用? br />
[注意:请不要介意,如果是学校的东西]
Without any use of object (objMyClass) outside a method, What is the use of object initializer, in this sample ?
[Note: Please don''t mind, if it is a school stuff]
推荐答案
理解为什么很简单它给出了错误:你试图在任何方法之外使用代码。
如果你将代码移动到一个方法中,那么它将起作用,但你可以放在方法之外的唯一一个是声明。如果你将两条线都移动到一个方法体中,那么你可以这样做 - 正如你在MyMethod中看到的那样。
有时你想要声明对象和尚未设置它的属性 - 因此默认构造函数存在。但是存在对象初始化语法以允许您指定属性值(并且您应该真正使它成为属性并明确地将其标记为公共或受保护而不是将其保留为默认访问字段),当您声明类实例时,假设没有允许它的构造函数。
通常,您将有一个特定的构造函数用于初始化,但组合的数量可能过多,因此对象初始化程序语法存在于绕过它。
(一般来说,我更喜欢创建特定的构造函数)
It''s pretty simple to understand why it gives the error: You are trying to use code outside any method.
If you move the code into a method, then it will work, but the only thing you can put outside a method is a declaration. If you move both lines into a method body, then you can do it - as you have seen with MyMethod.
There are times when you want to declare the object and not set it''s properties yet - so the default constructor exists for that. But the object initialiser syntax exists to allow you to specify property values (and you should really make it a property and explicitly mark it public or protected rather than leave it as a default access field) when you declare the class instance, assuming there is no constructor which allows it.
Normally, you would have a specific constructor for the initialisation, but the number of combinations can get too excessive, so the object initializer syntax exists to get round it.
(Generally, I prefer to create specific constructors)
这篇关于'objMyClass'是一个'字段'但是像'类型'一样使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文