类的默认属性 [英] Default Property Of A Class
本文介绍了类的默认属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我为名为Foo的实例创建了一个Class.如何设置默认属性,例如:
Hi,
If I have created a Class for instance named Foo. How do I set a default property so for instance:
Foo f = new Foo();
f = "Test";
是否可以不必使用构造函数或不必...
Is it possible without having to use a constructor or having to...
f.Name = "Test"
如果存在,则需要设置一个属性,或者应该在Foo类中调用基础属性以实现此目的?
在此先感谢.
If it is is there an Attribute that needs to be set or what should the underlying Propery be called in the Foo Class for this to happen?
Thanks in advance.
推荐答案
看看对象初始化程序 [ ^ ].
如果Foo类包含一个名为Name的属性,则可以执行Foo f = new Foo{Name="Test"}
Have a look at object initializers[^].
If you class Foo contains a property called Name, you can doFoo f = new Foo{Name="Test"}
C#中没有此类功能.许多C#人员甚至不理解您的问题,因为他们可能不熟悉其他一些语言中所知道的这个概念.我会说不是很大的损失...
—SA
There is no such feature in C#. Many C# people would not even understand your question because they might be unfamiliar with this concepts know in some other languages. Not a very big loss, I would say…
—SA
尽管我不愿意这样做,因为它打破了一些简单的OOP规则,您可以使用隐式运算符:
Despite I wouldn''t do it, as it breaks some simple rule of OOP, you can use an implicit operator :
public class Foo
{
public string Name { get; private set; }
public static implicit operator Foo(string s)
{
return new Foo { Name = s };
}
}
哪一个可以让你写:
Which would allow you to write :
Foo f = "some string";
但是,我还是不会这么做.
But, again, I wouldn''t do it.
这篇关于类的默认属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文