如何使用 if 语句创建属性 [英] How to make a property with a if-statement
本文介绍了如何使用 if 语句创建属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的问题是,如果可能的话,做这样的事情:
my question is, if it's possible, to do something like this:
public Class Test
{
public int Number { get; set; }
private string text;
public string Text
{
if (Number > 5)
{
set {text = value;}
get {return text;}
}
}
}
推荐答案
不,但你可以这样做:
public class Test {
public int Number { get; set; }
private string _Text;
public string Text {
get {
if(Number > 5) {
return _Text;
} else {
//DEFAULT value here.
return null;
}
}
set {
if(Number > 5) {
_Text = value;
} else {
//DEFAULT Value.
_Text = null;
}
}
}
}
如果您使用的是 Visual Studio,我还会查看预处理器指令.根据您尝试使用代码的方式,这些可能更有帮助.
I would also check out Preprocessor Directives if you are using Visual Studio. These might be more helpful depending on how you are trying to use the code.
预处理指令:https://msdn.microsoft.com/en-us/library/3sxhs2ty.aspx
这篇关于如何使用 if 语句创建属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文