0

我有一个控制器类,它有另一个类的私有字段,它是一个模型,模型从 xml 反序列化中获取数据。由于这个反序列化过程,我必须创建公共的、无参数的构造函数和一些公共字段助手,它们只是将数据格式处理为另一种类型。这个处理非常简单,我不想使用它的接口重写和 XmlSerialization 类。
我想要实现的是只能从模型继承的接口访问模型中的字段,但模型必须具有公共字段 - 如何隐藏其中一些?他们在同一个项目中。(整个应用程序是如此之小,以至于将其分成更小的部分并不总是有意义的)。

有一个例子:

public class Program
{
	public static void RequestHandler
	{
		
		public RequestHandler(string xmlRequest){
		IRequest request = DataModel.ParseXml(xmlRequest);
			
		//now user can use request from IRequest only
		//but when he doesn't know that he has to use IRequest he can easily access and change 
		//values in DataModel properties, I want to prevent such possibility
		
		}			
	}
}

public interface IRequest{
	
	int test_id { get; }
	DateTime description { get; }
	
	IRequest ParseXml(string request);
	bool Validate(IRequest request);
}

public class DataModel : IRequest {
	
	[XmlElement("testId")]
	int test_id { get; set; }
	
	[XmlElement("testId")]
	DateTime description { get; set; }

    public DataModel() {} //this has to be specified to be allowed to use Serialization
                          //I don't want users to be able to use this constructor, however it has to be public 
	
	IRequest static ParseXml(string request){
	     
		// Xml Parsing process	
	}
	
	bool Validate(IRequest request) {
		
		//Process of checking if all data are available
	}
	

}

4

1 回答 1

0

您能否将模型设为“内部”并仅通过多个接口公开所有字段并编写另一个类,该类将通过接口公开您的模型对象。例如

internal class DataModel : Interface1, Interface2 {

     internal DataModel(_xml)
     {
        this.xml = _xml;
     }

    private xml {get; set;}

    public Interface1.Property1 {get; set;}

    public Interface2.Property2 {get; set;}
}

//expose DataModel only via below Helper class
public class DataModelHelper {

   public Interface1 GetModel_1(string xml)
   {
    Interface1 i1 = new  DataModel(xml);
    return i1;
   }

   public Interface2 GetModel_2(xml)
   {
    Interface2 i2 = new  DataModel(xml);
    return i2;
   }
}
于 2015-11-18T10:20:30.953 回答