简体   繁体   中英

Default value for user defined class in C#

我看到一些代码会返回默认值,所以我想知道对于用户定义的类,编译器将如何定义其默认值?

To chime in with the rest, it will be null , but I should also add that you can get the default value of any type, using default

default(MyClass) // null
default(int) // 0

It can be especially useful when working with generics; you might want to return default(T) , if your return type is T and you don't want to assume that it's nullable.

class的默认值为null

Note: A DefaultValueAttribute will not cause a member to be automatically initialized with the attribute's value. You must set the initial value in your code.

You can decorate your properties with the DefaultValueAttribute.

private bool myVal=false;

[DefaultValue(false)]
 public bool MyProperty {
    get {
       return myVal;
    }
    set {
       myVal=value;
    }
 }

I know this doesn't answer your question, just wanted to add this as relevant information.

For more info see http://msdn.microsoft.com/en-us/library/system.componentmodel.defaultvalueattribute.aspx

The default value for classes is null . For structures, the default value is the same as you get when you instantiate the default parameterless constructor of the structure (which can't be overriden by the way). The same rule is applied recursively to all the fields contained inside the class or structure.

如果它是引用类型,则默认值将为null ,如果它是值类型,则它取决于。

I would make this "default" class instance a field rather than property, like how System.String.Empty looks:

public class Person 
{
    public string Name { get; set; }
    public string Address { get; set; }

    public static readonly Person Default = new Person() 
    {
        Name = "Some Name",
        Address = "Some Address"
    };
}

...

public static void Main(string[] args)
{
    string address = String.Empty;

    Person person = Person.Default;

    //the rest of your code
}
Assert.IsTrue(default(MyClass) == null);

If you are looking to somehow define a non-null default value for a reference type, realize that it wouldn't make sense for a reference type to have default value. At some point a reference would need to point to the allocated memory for the constructed object. To make it possible, I imagine two implementations:

  1. Define a static instance as the default: this could work but would probably require a really clunky way to somehow identify to the compiler where to get the static instance. Not really a feature worth putting into the language.

  2. Allow calling the default constructor every time the default value occurred in an expression: this would be terrible because now you have to worry about two default values possibly being unequal because you didn't override Equals to not compare references, and also terrible because of the memory management and memory allocation performance hit, and side affects from the constructor.

So in summary I think it is a language feature that we really don't want. And default(MyClass) will always == null.

For reference types or nullable value types the default will be null :

Person person = default; // = null
IEnumerable<Person> people = default; // = null
int? value = default; // = null

For value types, it depends on which value type it is:

int value = default; // = 0
DateTime dateTime = default; // = 1/1/0001 12:00:00 AM
Guid id = default; // = 00000000-0000-0000-0000-000000000000

Saving some other ppl's time, hopefully.

Obvious option nowadays (for which I still had to google a bit, as landed on this topic first) is to write an extention, that helps you to initialize a class, regardless of it's own complications (like constructor getters/setters, which prevent simple default value direct assignition).

Modifying previous answer a bit:

public class Person 
{
    public string Name { get; set; }
    public string Address { get; set; }

    public static readonly Person Default = new Person() 
    {
        Name = "Some Name",
        Address = "Some Address"
    };
}

=>

public class Person 
{
    public string Name { get; set; }
    public string Address { get; set; }
}
public static class PersonExtentions
{
    public static Person withDefaults(this Person obj) {
      obj.Name = "John Doe";
      return obj;
    }
}

And then

Person x = new Person.withDefaults();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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