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

时间:2016-10-05 14:38:58

标签: c# templates params

我正在尝试将params对象[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循环中,但我认为有一种更优雅的方式。有什么建议吗?

3 个答案:

答案 0 :(得分:4)

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

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()即可。这不仅是做事的好方法,而且在某些情况下性能有效(编译器可以极大地优化这个函数的一些调用)。

答案 1 :(得分:2)

泛型(<T>)和反射(.GetType())不是好朋友。没有方便的表达方式。但可以,滥用dynamic来执行此操作,在这种情况下您无法轻易使用ref。此外,您可以在refobject之间T。所以基本上,存在很多障碍。坦率地说,我认为你应该评估decodeValue<T>是否真的需要通用。在这种情况下 - 特别是在使用TypeDescriptor时 - 我非常怀疑它需要。我怀疑你最好的选择是:

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

答案 2 :(得分:0)

仿制药&#39;如果是GetType()用于运行时的编译时语法。你不能混合使用它们。

当source转换为二进制时,将解析泛型类。泛型中提供的类型或接口用于该区域。

相反,GetType在执行期间返回一个类型。该类型无法插入通用定义中,因为此时已完成编译。