追加字符串到< T>以产生一个新的类名字符串、lt、GT

2023-09-06 16:48:02 作者:奶昔

我如何追加字符串类型名称,然后将它作为另一种类型?下面是一个例子:

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;