如何将参数对象[i]传递给C#中的模板函数

How to pass params object[i] to a template function in C#

我正在尝试将参数对象[i] 发送到 T 函数,但找不到正确的语法。

这里有一个例子来展示我正在努力实现的目标:

private bool decodeValue<T>(int id,ref T item, string code)
{

    if(!TypeDescriptor.GetConverter (item).CanConvertFrom(typeof(string)))
    {
        errorThrow (id + 2);
        return false;
    }

    try
    {
        item = ((T)TypeDescriptor.GetConverter (item).ConvertFromString (code));
    }
    catch 
    {
        errorThrow (id + 2);
        //item = default(T);
        return false;
    }

    return true;
}

private bool decodeValues(string[] code, int id, params object[] items)
{
    for (int i = 0; i < items.Length; i++) 
    {
        System.Type t = items [i].GetType(); 
        //in this part i cant find the correct syntax
        if(decodeValue<(t)items[i]>(id, ref items[i] as t, code[i+2]))
        {

        }
    }

    return false;
}

在第decodeValue<(t)items[i]>(id, ref items[i] as t, code[i+2]行 无论我尝试什么语法,编译器都会告诉我在 > 之后它需要一个 )

我可以将函数 decodeValue 内联到 for 循环中,但我认为有一种更优雅的方法可以做到这一点。有什么建议吗?

泛型(<T>)和反射(.GetType())不是好朋友。没有方便 的表达方式。你可以,然而,滥用dynamic来做到这一点,但是在那种情况下你不能轻易使用ref .此外,您不能在 objectT 之间 ref。所以基本上,有很多障碍。坦率地说,我认为您应该评估 decodeValue<T> 是否真的需要通用。在这种情况下——尤其是在使用 TypeDescriptor 时——我非常怀疑是否需要这样做。我怀疑你最好的选择是:

private bool DecodeValue(int id, ref object item, Type type, string code)

在您的示例中,您替换了项目的内容。为什么甚至需要模板化功能?只需这样做:

private bool decodeValue(int id,ref object item, string code)
{

    if(!TypeDescriptor.GetConverter(item).CanConvertFrom(typeof(string)))
    {
        errorThrow (id + 2);
        return false;
    }
    try
    {
        item = TypeDescriptor.GetConverter(item).ConvertFromString(code);
    }
    catch 
    {
        errorThrow (id + 2);
        return false;
    }

    return true;
}

private bool decodeValues(string[] code, int id, params object[] items)
{
    for (int i = 0; i < items.Length; i++) 
    {
        //in this part i cant find the correct syntax
        if(decodeValue(id, ref items[i], code[i+2]))
        {

        }
    }

    return false;
}

如果您在代码中需要项目类型,只需在实际需要的地方调用 .GetType() 即可。这不仅是做事的好方法,而且在某些情况下性能有效(编译器可以极大地优化此函数的某些调用)。

泛型语法用于编译时,而 GetType() 用于运行时。您不能混合使用它们。

通用 class 在您将源代码转换为二进制文件时得到解决。通用类型中提供的类型或接口在该区域中使用。

反之GetType returns执行时的类型。该类型不能插入通用定义中,因为此时已经完成了编译。