追加字符串到&lt; T&GT;以产生一个新的类名 [英] Appending string to <T> to produce a new class name
本文介绍了追加字符串到&lt; T&GT;以产生一个新的类名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我如何追加字符串类型名称,然后将它作为另一种类型?下面是一个例子:
How do I append string to a type name then pass it as another type? Here is an example:
public T Get<T>(int id)
{
return dbAccess.Get<T>(id);
}
如果我把这种方法就像
SomeObject.Get<Class1>(1234);
我想改变 1级
是 Class1Data code>通过将字符串数据的任何传递类,所以
dbAccess.Get
方法要为对象为 Class1Data code>为
的转换1级
。
I would like to change Class1
to be Class1Data
by appending the string "Data" to any passed class, so the dbAccess.Get
method would take the object as Class1Data
as a conversion of Class1
.
推荐答案
像这样的工作:
public T Get<T>(int id)
{
var newTypeName = typeof(T).FullName + "Data";
var newType = Type.GetType(newTypeName);
var argTypes = new [] { newType };
var method = GetType().GetMethod("Get");
var typedMethod = method.MakeGenericMethod(argTypes);
return (T) typedMethod.Invoke(this, new object[] { id });
}
如果您的XxxData对象不从xxx继承,您可能希望在返回结果前做一些自动映射。
In case your XxxData object don't inherit from Xxx, you may want to do some automapping before returning the result.
然后你将不得不在最后一行替换为:
Then you would have to replace the last line to:
var dataResult = typedMethod.Invoke(this, new object[] { id });
var result = new T(); // You will have to add a new() constraint on generic parameter
// Map your dataResult object's values onto the result object's values
return result;
这篇关于追加字符串到&lt; T&GT;以产生一个新的类名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文