简体   繁体   English

如何确保为通过Web服务公开的类的属性设置初始值

[英]How to ensure initial values are set for properties of a class exposed via a webservice

I have a class which initializes its properties in its constructor. 我有一个在其构造函数中初始化其属性的类。

public class Criteria
{
    public bool Chapter1 { get; set; }
    public bool Chapter2 { get; set; }
    ...
    public uint MaxResults { get; set; }
    public int Hits { get; set; }

    public Criteria()
    {
        Chapter1 = false;
        Chapter2 = false;
        ...
        MaxResults = 100;
        Hits = -1;
    }
}

This class is used internally within a web-service to configure searches on a DB. 此类在Web服务内部使用,用于配置数据库上的搜索。 When I construct the class internally, the correct initialization is performed and operation is as anticipated. 当我在内部构造类时,将执行正确的初始化,并按预期进行操作。

However, the class is also exposed as a parameter in a Method to this Web-Service : 但是,该类也作为此方法的参数公开给此Web服务:

    [WebMethod]
    public List<xxx> GetxxxCollection(string requestingUserName, Criteria sc)
    {
      ...
    }

Prior to the clients call to this web-service, the Criteria object is constructed and configured. 在客户端调用此Web服务之前,将构造和配置Criteria对象。 But, because its exposed through the web-service, the constructor is not actually called and the client does not always set all required values correctly. 但是,由于构造函数实际上是通过Web服务公开的,因此实际上并未调用该构造函数,并且客户端不一定总是正确设置所有必需的值。

Given that we have limited control over the client code, Whats the best strategy to ensure that appropriate initial values are set ? 鉴于我们对客户端代码的控制有限,确保适当的初始值设置的最佳策略是什么?

You cannot control the client in any way. 您无法以任何方式控制客户端。 The "Service" class on the client is in no way related to the service class that contains the constructor. 客户端上的“服务”类与包含构造函数的服务类没有任何关系。 It's just a "proxy" class, not the real thing. 这只是一个“代理”类,不是真实的东西。

也许您可以使用nullablenullable字段,以便您知道客户端尚未在这些字段中设置任何值。

Don't use auto-implemented properties in your class, but instead use the old manual properties with backing-fields which might be initialized by default without a constructor invocation: 不要在类中使用自动实现的属性,而应将旧的手动属性与支持字段一起使用,这些默认情况下可能会在没有构造函数调用的情况下进行初始化:

public class Criteria
{
  private int _maxResults = 100;

  //-----------------------------------------------------------------------

  public int MaxResults
  {
    get{ return _maxResult; }
    set{ _maxResults = value; }
  }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM