将类作为参数传递给方法 [英] Pass class as a parameter to method
本文介绍了将类作为参数传递给方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我无法完成此方法。我如何传递类作为参数,并返回相同的类?
这是我见过的场景
I'm having trouble finishing this method. How can I pass class as parameter and return the same class? This is the scenario I've met
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?;
}
}
任何帮助
推荐答案
在语法上你会使用泛型:
Well syntactically you'd use generics:
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);
这篇关于将类作为参数传递给方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文