【问题标题】:Pass class as a parameter to method将类作为参数传递给方法
【发布时间】:2014-12-11 01:20:10
【问题描述】:

我无法完成此方法。如何将类作为参数传递并返回相同的类? 这是我遇到的场景

Class A
{
...
}

Class C
{
 ....
}

Class B
{
  A a = getJSONClass(String jsonString, classA?);
  C c = getJSONClass(String jsonString, classC?);

  public (class?) getJSONClass(String jsonString, class?)
  {
   MemoryStream memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
   DataContractJsonSerializer ser = new DataContractJsonSerializer(class?.type);
   return ser.ReadObject(memoryStream) as class?;
  }

}

有什么帮助吗??

【问题讨论】:

    标签: c# class parameters


    【解决方案1】:

    在语法上你会使用泛型:

    public T getJSONClass<T>(String jsonString) where T : class
    {
       MemoryStream memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
       DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
       return ser.ReadObject(memoryStream) as T;
    }
    

    用法:

    A a = getJSONClass<A>(String jsonString);
    C c = getJSONClass<C>(String jsonString);
    

    【讨论】:

    • 我认为您需要对T 进行class 约束才能使用as T? (但仍然 +1)。
    【解决方案2】:

    使用generics:

        public T GetDeserializedObject<T>(string jsonString) where T: class
        {
            var serializer = new DataContractJsonSerializer(typeof(T));
    
            using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(jsonString)))
            {
                return serializer.ReadObject(stream) as T;
            }
        }
    

    【讨论】:

      【解决方案3】:

      你不能这样做吗:

      Class A
      {
      ...
      }
      
      Class C
      {
       ....
      }
      
      Class B
      {
        A a = (A)getJSONClass(String jsonString, typeof(A));
        C c = (C)getJSONClass(String jsonString, typeof(C));
      
        public object getJSONClass(String jsonString, Type type)
        {
         MemoryStream memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
         DataContractJsonSerializer ser = new DataContractJsonSerializer(type);
         return ser.ReadObject(memoryStream);
        }
      }
      

      【讨论】:

        猜你喜欢
        • 2015-12-26
        • 2018-12-11
        • 1970-01-01
        • 1970-01-01
        • 2021-02-05
        • 2022-01-22
        • 1970-01-01
        • 2013-01-28
        • 1970-01-01
        相关资源
        最近更新 更多