繁体   English   中英

如何在C#中将params object [i]传递给模板函数

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

我正在尝试将params object [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]无论我尝试使用哪种语法,编译器都告诉我在>之后需要a )

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

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

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

泛型( <T> )和反射( .GetType() )不是好朋友。 没有方便的表达方式。 可以 ,但是,滥用dynamic做到这一点, 你不能轻易使用ref在这种情况下。 此外,您不能在objectT之间进行ref 所以基本上,有很多障碍。 坦白说,我认为您应该评估一下是否确实需要使用decodeValue<T> 在这种情况下-特别是在使用TypeDescriptor -我非常怀疑它是否需要。 我怀疑您最好的选择是:

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

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

将源转换为二进制时,将解析通用类。 该区域使用通用类型提供的类型或接口。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM