我如何追加字符串类型名称,然后将它作为另一种类型?下面是一个例子:
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 通过将字符串数据的任何传递类,所以
dbAccess.Get
方法要为对象为 Class1Data 为
的转换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;
上一篇:Twitter的回调并登录使用Jtwitter回调、Twitter、Jtwitter
下一篇:Heroku 无法将我的 Laravel 应用程序识别为 PHP 应用程序,并且不执行 composer install应用程序、我的、Laravel、Heroku