[英]How to make these n methods to a single generic method?
我有一个这样的基类:
public class BaseResponse
{
public string ErrorMessage { set;get;}
}
还有一些继承自此的子类:
public class Person:BaseResponse
{
public string FirstNAme { set;get;}
}
public class Phone:BaseResponse
{
public string SerialNumber { set;get;}
}
public class Car :BaseResponse
{
public string Year{ set;get;}
}
现在,我想将此类的每个实例的ErrorMessage
属性设置为不同的值。 目前,这是我在做什么:
public Phone GetPhoneError(Phone objPhone)
{
objPhone.ErrorMessage="Err msg related to Phone";
return objPhone;
}
public Person GetPersonError(Person objPerson )
{
objPerson .ErrorMessage="Err msg related to Person";
return objPerson ;
}
... another similar method for Car also
有什么方法可以使该方法成为通用格式,这样就不需要3种单独的方法来设置错误消息了?
public T GetError<T>(T obj) where T: BaseResponse
{
obj.ErrorMessage= string.Format("Err msg related to {0}", typeof(T).Name);
return obj;
}
我不知道错误消息是此通用消息还是自定义消息。 如果是这样,则将消息作为参数传递。
为什么需要为此的方法? 是因为您简化了问题吗?
因此,在基类中,您应该创建一个名为SetError的虚拟方法(您的GetError,但使用正确的符号)。
public abstract string GetErrorMessage(); //In Base Class so that why each implementation will set the correct error message
然后在您的基类中-为什么还要返回要修改的相同对象?
public virtual void SetErrorMessage()
{
this.ErrorMessage = GetErrorMessage();
}
您应该能够有一个像这样的通用方法:
public object GetError(BaseResponse response)
{
response.ErrorMessage = "whatever";
return response;
}
在这种情况下,为什么不将属性virtual
并且不需要set
? :
public class BaseResponse
{
public virtual string ErrorMessage { get;}
}
public class Person:BaseResponse
{
.....
public override string ErrorMessage {get { return "Err msg related to Person";}}
}
public class Phone:BaseResponse
{
......
public override string ErrorMessage {get { return "Err msg related to Phone";}}
}
对其他人等等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.