【发布时间】:2020-07-05 14:49:38
【问题描述】:
我有这个通用函数
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约束,你还可以有一个委托来对创建的对象应用任何操作