naw*_*fal 15 .net c# overriding default
可能重复:
如何更改默认(T)在C#中返回的内容
print(default(int) == 0) //true
Run Code Online (Sandbox Code Playgroud)
同样,如果我有一个自定义对象,它的默认值将为null.
print(default(Foo) == null) //true
Run Code Online (Sandbox Code Playgroud)
我可以为自定义值default(Foo)而不是null吗?
例如,像这样:
public static override Foo default()
{
return new Foo();
}
Run Code Online (Sandbox Code Playgroud)
这不会编译.谢谢..
坦率地说,这不是一个真正的答案,而是一个简单的提及.如果Foo是一个结构,那么你可以有这样的东西:
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;
}
Run Code Online (Sandbox Code Playgroud)
[TestClass]
public class FooTest
{
[TestMethod]
public void TestDefault()
{
var o = default(Foo);
Assert.AreEqual("Default text...", o.Text);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10880 次 |
| 最近记录: |