C# 如何创建返回具有特定参数的对象的工厂?
我有这个通用函数C# 如何创建返回具有特定参数的对象的工厂?,c#,oop,factory,C#,Oop,Factory,我有这个通用函数 private static T PostNew<T>() where T : IHttpModel, new() { var t = HttpModelsFactory.Create<T>(); var requestT = new RestRequest("/households", Method.POST); requestT.AddParameter("appl
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;
}
private static T PostNew(),其中T:IHttpModel,new()
{
var t=HttpModelsFactory.Create();
var requestT=新的重新请求(“/houses”,Method.POST);
AddParameter(“application/json”,t.ToJson(),ParameterType.RequestBody);
返回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()
};
}
}
class HttpModelsFactory
{
公共静态T Create(),其中T:IHttpModel,new()
{
typeofT=typeof(T);
if(typeofT.等于(typeof(住户)))
{
将createHousehouse()返回为T;
}
}
公共静态住户CreateHouse()
{
还新家
{
Name=Randoms.RandomString()
};
}
}
这将有更多的课程,而不仅仅是家庭课程。但是,它目前给了我一个错误:“类型参数'T'不能与'as'运算符一起使用,因为它既没有类类型约束,也没有'class'约束。”我如何重构代码使其工作,或者有更好的解决方案?添加
类
约束,您还可以使用委托对创建的对象应用任何操作
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;
}
}
添加
class
约束,您还可以让一个委托对创建的对象应用任何操作谢谢!这似乎是解决办法。因此,我将在PostNew方法中执行操作。编辑:当我写这篇评论时,答案仍然没有被编辑。
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;
}
//...
var result = PostNew<Household>(h => {
h.Name = Randoms.RandomString();
});
//...