为什么不进入方法就不能设置类对象的属性值? [英] Why can't I set the property value of a class object without being in a method?

查看:30
本文介绍了为什么不进入方法就不能设置类对象的属性值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在设置属性时遇到麻烦,意识到我只能在函数或方法中设置属性.我的问题是为什么会这样?

I was having trouble setting properties and realized I could only set the properties within a function or method. My question is why is this the case?

这是我的有效代码:

public class SomeClass
{    
    Car car = new Car();

    public Car JustAMethod()
    {
        Car car = new Car();
        car.year = 2012;

        return car;
    }        
}

为什么这个方法行不通:

Why doesn't this work:

public class SomeClass
{        
    Car car = new Car();
    car.year = 2012;//I get an error here
}

推荐答案

(大多数情况下)语言规范禁止在类级别执行任意语句.所有可以做的就是为类的静态或实例成员指定默认值.

The language specification (for the most part) forbids the execution of arbitrary statements at the class level. All that can be done is to specify default values for static or instance members of the class.

一般而言,所有代码都必须在类的方法内执行.

All code, generally speaking, must be executed within methods of a class.

正如AntLaC所述,您可以通过使用对象初始化语法指定值来解决此问题.由于可以在类级别上定义对象(作为静态或实例成员的默认值"),因此使用下面的语法也可以:

As AntLaC mentioned, you can get around this by specifying the value using the object initialization syntax. Since objects can be defined at the class level (as "default values for static or instance members"), using syntax like the below will also work:

public class SomeClass
{
    Car car = new Car() {
        year = 2012;
    };
}

这篇关于为什么不进入方法就不能设置类对象的属性值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆