【问题标题】:How to create a Factory that returns an object with specific parameters?如何创建一个返回具有特定参数的对象的工厂?
【发布时间】: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约束,你还可以有一个委托来对创建的对象应用任何操作

标签: c# oop factory


【解决方案1】:

添加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;
    }
}

然而,现在这意味着它需要冒泡到使用它的地方。

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();
});

//...

【讨论】:

  • 谢谢!这似乎是解决方案。所以我将在 PostNew 方法中使用 Action。编辑:当我写这篇评论时,答案还没有被编辑。
猜你喜欢
  • 2019-10-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-07-22
  • 1970-01-01
  • 2018-01-11
  • 1970-01-01
  • 2011-09-30
相关资源
最近更新 更多