c# - 是否有通过泛型类使用静态方法的解决方法?

标签 c# generics reflection

我有一个相当简单的问题,但在 C# 中似乎没有解决方案。

我有大约 100 个 Foo 类,每个类都实现了一个 static FromBytes() 方法。还有一些通用类应将这些方法用于其自己的 FromBytes()。但是泛型类不能使用 static FromBytes() 方法,因为 T.FromBytes(...) 是非法的。

我是否遗漏了什么或者没有办法实现此功能?

public class Foo1
{
    public static Foo1 FromBytes(byte[] bytes, ref int index)
    {
        // build Foo1 instance
        return new Foo1()
        {
            Property1 = bytes[index++],
            Property2 = bytes[index++],
            // [...]
            Property10 = bytes[index++]
        };
    }

    public int Property1 { get; set; }
    public int Property2 { get; set; }
    // [...]
    public int Property10 { get; set; }
}

//public class Foo2 { ... }
// [...]
//public class Foo100 { ... }

// Generic class which needs the static method of T to work
public class ListOfFoo<T> : System.Collections.Generic.List<T>
{
    public static ListOfFoo<T> FromBytes(byte[] bytes, ref int index)
    {
        var count = bytes[index++];
        var listOfFoo = new ListOfFoo<T>();
        for (var i = 0; i < count; i++)
        {
            listOfFoo.Add(T.FromBytes(bytes, ref index)); // T.FromBytes(...) is illegal
        }

        return listOfFoo;
    }
}

我认为选择一个答案作为接受的答案是不公平的,毕竟所有的答案和评论都以不同的方式做出了不同的贡献。如果有人对不同方法及其优缺点进行了很好的概述,那就太好了。在最好地帮助 future 的开发人员之后,应该接受它。

最佳答案

最好的选择是简单地接受特定的 FromBytes 函数作为通用 FromBytes 函数的委托(delegate)。这避免了使用反射带来的性能成本和缺乏编译时可验证性。

public delegate T FromBytesFunc<T>(byte[] bytes, ref int index);
public static List<T> FromBytes<T>(byte[] bytes, ref int index,
    FromBytesFunc<T> function)
{
    var count = bytes[index++];
    var listOfFoo = new List<T>();
    for (var i = 0; i < count; i++)
    {
        listOfFoo.Add(function(bytes, ref index));
    }

    return listOfFoo;
}

请注意,如果您将方法(而不是它所在的类)设为泛型,则可以让编译器推断出泛型参数。可以这样称呼:

var list = SomeClass.FromBytes(bytes, ref index, Foo1.FromBytes);

关于c# - 是否有通过泛型类使用静态方法的解决方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19907413/

相关文章:

c# - 我得到统一的错误CS1061(您是否缺少using指令或程序集引用?)

c# - 通过通用方式创建任何 C# 类的实例

java - 为什么不允许这样使用泛型和通配符?

java - 使用 Map 填充 Java 对象

c# - 按依赖项对 .NET 程序集进行排序

c# - 将扩展方法限制为基类

c# - 我什么时候应该在 C# 中使用 IEnumerator 进行循环?

c# - WPF/Silverlight 程序员 : Is MVVM Overkill?

Java 泛型 - 将函数映射到列表

c# - 非公共(public)事件的 EventInfo.AddEventHandler 的替代方法