输入参数webservice方法



我有一个名为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

我不了解

感谢

这应该是意料之中的事。当您创建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");   
}

如果您使用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");
   }

}

最新更新