我想知道是否有一种方法可以知道是否已设置参数。例如,我有对象User。
public class User{
public int Oid{ get; set; }
public string Name{ get; set; }
public string Test{ get; set; }
}
我创建对象的实例,并设置属性Oid和Name,但未设置Test。我想知道这一点。
User u = new User();
u.Oid = 1;
u.Name = "Test";
有可能吗?
TY
答案 0 :(得分:1)
对于引用类型,未设置的属性(或字段)将具有值null
。由于string
是引用类型,因此可以非常方便地进行检查:
if(u.Test == null)
{
Console.WriteLine("Property test of variable u is not set!");
}
对于其他类型,并不是那么容易。 bool
变量在默认情况下将为false,并且所有数字值,例如int
uint
,double
等均为0。但是,当然,有人可能将其设置为完全意识到这些值。
您可以通过以下方法获取任何类型的默认值:
int x = default(int); // will be 0
string y = default(y); // will be null
bool z = default(bool); // will be false;
附录:以下是完全不同的方法:
public class User{
public int Oid{ get; set; }
public string Name{ get; set; }
private string test;
public string Test
{
get { return test; }
set {test = value; IsTestSet = true; }
}
public bool IsTestSet {get; private set;}
}
使用此代码,您可以检查属性IsTestSet
以确定设置程序是否至少被调用过一次。
答案 1 :(得分:0)
这是我的个人解决方案。
public short oid;
public short Oid
{
get { return oid; }
set
{
oid = value;
AddListaSet("Oid");
}
}
// for all parameter
List<string> ListSet { get; set; } = new List<string>();
private void AddListSet(string name)
{
if (ListSet.Contains(name) == false)
ListSet.Add(name);
}
public bool IsSet(string name)
{
return ListSet.Contains(name) ? true : false;
}