简体   繁体   English

为属性分配默认值

[英]Assign default value to property

I have the following class property: 我具有以下类属性:

public String Url { get; set; }

I would like it to return a default value in case it wasn't defined. 我希望它在未定义的情况下返回默认值。

I do not want to return String.Empty when it wasn't defined. 我不想在未定义时返回String.Empty。

I am using the NET 4.5. 我正在使用NET 4.5。

What is the best way to do this? 做这个的最好方式是什么?

Thank You, Miguel 谢谢米格尔

well to be honest i dont know if it is the best answeer and well this is my first asweer here, but that is besides the point. 老实说,我不知道这是否是最好的答案,这是我在这里的第一个答案,但这不重要。 i whould do it like this 我会这样做

class Class1
{
    string sUrl = "www.google.com";
    public string Url
    {
        get
        {
            return sUrl;
        }
        set
        {
            sUrl = value;
        }
    }
}

now you have a string value behind the property that has a default of www.google.com 现在,该属性后面有一个字符串值,该字符串值的默认值为www.google.com

hope this helps 希望这可以帮助

Just set the default value in the class constructor. 只需在类构造函数中设置默认值即可。

public class MyClass
{

     public MyClass()
     {
        MyProperty = 22;
     }


     public int MyProperty { get; set; }

     ...
}

You can create a backing field: 您可以创建一个支持字段:

private string _url = "myUrl"

public String Url
{
    get { return _url; }
    set { _url = value; }
}

For a non static field, we can only set the default value after the object is constructed. 对于非静态字段,我们只能在构造对象之后设置默认值。 Even when we inline a default value, the property is initialized after construction. 即使我们内联默认值,该属性也会在构造后初始化。

For automatic properties, constructor is the best place to initialize. 对于自动属性,构造函数是初始化的最佳位置。 Maybe you can do it in the default constructor and then have additional constructors as required. 也许您可以在默认构造函数中执行此操作,然后根据需要添加其他构造函数。

Another option would be to use reflection - but that is more than an overkill. 另一种选择是使用反射-但这不算过分。

You can initialize your property inside your default constructor AND do not forget to call the default constructor inside other constructors (in this example MyClass(int) ), otherwise the field will not be initialized. 您可以在默认构造函数中初始化属性,并且不要忘记在其他构造函数(在本示例中为MyClass(int) )中调用默认构造函数,否则该字段将不会初始化。

class MyClass
{
    public MyClass()
    {
        this.Url = "http://www.google.com";
    }

    public MyClass(int x)
        : this()
    {
    }

    public String Url { get; set; }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM