在自动生成的属性实例化对象 [英] Instanciate object in auto-generated property

查看:143
本文介绍了在自动生成的属性实例化对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在不实例化它在构造函数中自动实例化一个对象。

Is there a way to instanciate an object automatically without instanciate it in the constructor ?

其实,我有这样的:

public List<Object> Products { get; set; }
public MyClass()
{
    this.Products = new List<Object>();
}



不过,我后来想直接实例化我的列表,而在我的构造函数指定我喜欢的东西类的:

But instead, I would like to instanciate directly my list without specifying in my constructor of my class with something like :

public List<Object> Products = new List<Object>(); { get; set; }



有没有窍门这样做呢?

Is there any trick to do this?

推荐答案

由于乔恩斯基特说:

这是不幸的,有没有这样做的权利的方式现在。你有
设置在构造函数的值。 (使用构造函数链可以
有助于避免重复。)

It's unfortunate that there's no way of doing this right now. You have to set the value in the constructor. (Using constructor chaining can help to avoid duplication.)

自动实现的属性是很方便的权利,但可以
肯定会更好。我不觉得自己经常想这种
初始化因为这只能在构造函数中设置只读自动实现
属性和将是
。通过一个只读的备份领域。这有可能是这两个将是
固定在C#5,我强烈希望将解决不变性
的担忧。 (我不认为他们俩都安排在C#4)

Automatically implemented properties are handy right now, but could certainly be nicer. I don't find myself wanting this sort of initialization as often as a read-only automatically implemented property which could only be set in the constructor and would be backed by a read-only field. It's possible that both of these will be fixed in C# 5, which I strongly hope will address immutability concerns. (I don't think either of them are scheduled for C# 4.)

来源:的Initializing~~V C#自动性能

如果您需要初始化属性 不使用构造,您需要使用支持字段

If you need to initialize the property without using the constructor, you need to use a backing field.

示例

class Demo
{
    private List<object> myProperty = new List<object>();
    public List<object> MyProperty
    {
        get { return myProperty; }
        set { myProperty = value; }
    }
}

这篇关于在自动生成的属性实例化对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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