How to override default(T) in C#? [duplicate]

夙愿已清 提交于 2020-01-10 04:49:06

问题


Possible Duplicate:
Howto change what Default(T) returns in C#

print(default(int) == 0) //true

Similarly if I have a custom object, its default value will be null.

print(default(Foo) == null) //true

Can I have a custom value for default(Foo) and not null?

For example, something like this:

public static override Foo default()
{
    return new Foo();
}

This wont compile. Thanks..


回答1:


You can't override the default(T) keyword. It is always null for reference types and zero for value types.

More Information

  • MSDN - default Keyword in Generic Code (C# Programming Guide)



回答2:


Doesn't seem like it. From the documentation:

default ... will return null for reference types and zero for numeric value types. For structs, it will return each member of the struct initialized to zero or null depending on whether they are value or reference types.




回答3:


Frankly, it's not a real answer but a simple mention. If Foo was a struct so you can have something like this:

public struct Foo
{

    public static readonly Foo Default = new Foo("Default text...");

    public Foo(string text)
    {
        mText = text;
        mInitialized = true;
    }

    public string Text
    {
        get
        {
            if (mInitialized)
            {
                return mText;
            }
            return Default.mText;
        }
        set { mText = value; }
    }

    private string mText;
    private bool mInitialized;

}

[TestClass]
public class FooTest
{

    [TestMethod]
    public void TestDefault()
    {
        var o = default(Foo);

        Assert.AreEqual("Default text...", o.Text);
    }

}


来源:https://stackoverflow.com/questions/12793418/how-to-override-defaultt-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!