问题
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