使用泛型T的DefineMethod

时间:2015-05-09 19:44:14

标签: c# cil reflection.emit

  

类型或命名空间名称' T'无法找到

如何在参数中使用T

Type[] tparams = { typeof(Expression<Func<T, object>>) };
MethodBuilder methodId = tbuilder.DefineMethod("Id", MethodAttributes.Public, typeof(IdentityPart), tparams);

2 个答案:

答案 0 :(得分:2)

代码必须是通用方法的一部分:

方式:

public void Method<T>()
{
    // code snnipet
    Type[] tparams = { typeof(Expression<Func<T, object>>) };
}

<强>类别:

public class Class<T>
{
    public void Method()
    { 
        // code snnipet
        Type[] tparams = { typeof(Expression<Func<T, object>>) };
    }
}

答案 1 :(得分:1)

您可以使用辅助方法作为填写类型参数的工具。假设您希望T成为名为MyVerySpecialType的类:

SELECT i.*, c.*
FROM invoices i
JOIN customer c
ON c.invoice = i.invoice
ORDER BY i.invoice

然后你可以这样做:

public static class Helper
{
    public static Type[] TypeArrayReturnerWithGeneric<T>()
    {
        return new Type[] { typeof(Expression<Func<T, object>>) };
    }
}