在创建泛型类型的实例时无法提供参数

goo*_*ate 17 c# generics json encapsulation

我有一个对象,我想在创建后才能读取...因为构造函数中的属性必须在GetHashCode中使用,因此一旦创建就不能更改.

我是readonly的许多类之一:

public class AccountLabel
{ 
    private string result;

    public AccountLabel(string result)
    {
        // TODO: Complete member initialization
        this.result = result;
    }

    public string JSONRPCData { get { return this.result; } }
}
Run Code Online (Sandbox Code Playgroud)

我有这样的通用结果类

  public  class JsonResult<T>  where  T : JObject, new()
  {
    private T bhash;
    private string p;
    private JsonErrorResponse error;
    private int _id;
    private Newtonsoft.Json.Linq.JObject ret;

    public JsonResult(Newtonsoft.Json.Linq.JObject ret)
    { 
        this.ret = ret;

        var tempError = ret["error"];
        var tempid = ret["id"];
        JsonErrorResponse error = new JsonErrorResponse(tempError);
        this.error = error;
        this._id = 1;


        var tempresult = ret["result"];
        T someResult = new T(tempresult);  // <--- here is my problem
    }
Run Code Online (Sandbox Code Playgroud)

我的问题是我想将一个对象传递给T的构造函数但不能.当我输入这个时,编译器会告诉我Cannot provide arguments when creating an instance of variable type

解决这种情况的最佳方法是什么?

  • 我应该有一个可以调用的接口来更新属性吗?

  • 以前的接口是否会破坏封装或允许对我的对象进行更改?

  • 我该怎么办呢?

das*_*ght 27

您可以删除new类型约束,然后使用Activator.CreateInstance.

而不是这个

T someResult = new T(tempresult);
Run Code Online (Sandbox Code Playgroud)

写这个:

T someResult = (T)Activator.CreateInstance(
    typeof(T)
,   new object[] { tempresult }
);
Run Code Online (Sandbox Code Playgroud)

由于经历了反射,这可能会稍慢,并且编译器的静态检查将不会执行.但是,考虑到您的情况,看起来这些都不会产生重大问题.


jam*_*eff 7

您可以将工厂委托传递给以下构造函数JSonResult<T>:

public class JsonResult<T> where T : JObject
{
    public JsonResult(Newtonsoft.Json.Linq.JObject ret, Func<object, T> factory)
    { 
        var tempresult = ret["result"];
        T someResult = factory(tempresult);
    }
}
Run Code Online (Sandbox Code Playgroud)

objectin Func<object, T>可以替换为tempResult实际的类型.