我有一个名为MyMethodQuery的类,它包含一个属性和一个构建器,该构建器将检查属性是否正确填充:
public class MyMethodQuery
{
public string Id { get; set; }
public MyMethodQuery ()
{
if (string.IsNullOrEmpty(this.Id))
throw new System.ArgumentException("Parameter cannot be null");
}
}我的方法是:
public string MyMethod(MyMethodQuery MyMethodQuery)
{
return "it's ok !";
}当我使用id调用我的方法时,我填充了一个抛出的异常:
An exception of type 'System.ArgumentException' occurred
Additional information: Parameter can not be null我什么都不了解
谢谢
发布于 2015-12-21 06:07:25
这应该是意料之中的。创建MyMethodQuery的新实例时,将调用该类的构造函数,此时ID字段仍为空
您可以更改构造函数以接收初始值
public class MyMethodQuery
{
public string Id { get; set; }
public MyMethodQuery(string initialValue = "1")
{
this.Id = initialValue;
if (string.IsNullOrEmpty(this.Id))
throw new System.ArgumentException("Parameter cannot be null");
}
}当然,如果您使用与类名不同的名称调用变量,那么理解您的代码会很有帮助
void Main()
{
MyMethodQuery anInstance = new MyMethodQuery("1");
}发布于 2015-12-21 06:10:00
如果您使用的是c#6,则可以直接初始化自动属性
public class MyMethodQuery
{
public string Id { get; set; } = "Inialized";
public MyMethodQuery ()
{
if (string.IsNullOrEmpty(this.Id))
throw new System.ArgumentException("Parameter cannot be null");
}}
https://stackoverflow.com/questions/34386359
复制相似问题