我有这个通用函数
private static T PostNew<T>() where T : IHttpModel, new()
{
var t = HttpModelsFactory.Create<T>();
var requestT = new RestRequest("/households", Method.POST);
requestT.AddParameter("application/json", t.ToJson(), ParameterType.RequestBody);
return t;
}
它需要创建并发送类型为 T 的对象。但是,该对象需要具有特定的属性,具体取决于类型。
class HttpModelsFactory
{
public static T Create<T>() where T : IHttpModel, new()
{
Type typeofT = typeof(T);
if (typeofT.Equals(typeof(Household)))
{
return CreateHousehold() as T;
}
}
public static Household CreateHousehold()
{
return new Household
{
Name = Randoms.RandomString()
};
}
}
这将有更多的类别,而不仅仅是家庭。然而,它目前给了我这个错误:“类型参数‘T’不能与‘as’运算符一起使用,因为它没有类类型约束,也没有‘类’约束。”如何重构代码以使其正常工作或者是否有更好的解决方案?
最佳答案
添加class
约束,您还可以有一个委托(delegate)来对创建的对象应用任何操作
class HttpModelsFactory {
public static T Create<T>(Action<T> configure = null)
where T : IHttpModel, class, new() {
T result = new T();
if(configure != null) configure(result);
return result;
}
}
但是现在这意味着它需要冒泡到使用的地方。
private static T PostNew<T>(Action<T> configure = null)
where T : IHttpModel, class, new() {
var model = HttpModelsFactory.Create<T>(configure);
var request = new RestRequest("/households", Method.POST);
request.AddParameter("application/json", model.ToJson(), ParameterType.RequestBody);
//...
return model;
}
导致对 PostNew
的调用可能类似于
//...
var result = PostNew<Household>(h => {
h.Name = Randoms.RandomString();
});
//...
关于c# - 如何创建一个返回具有特定参数的对象的工厂?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62742243/