我有一个控制器类,它有另一个类的私有字段,它是一个模型,模型从 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
}
}