具有基于静态成员的类型约束的泛型

Generics with type constraints based on static members

我正在尝试使用带有似乎不受支持的约束的泛型,我想知道是否有一个干净的解决方法。

我最初尝试的问题在于接口中不能有静态成员,因此不能使用接口来约束基于静态成员的泛型声明中的类型。

考虑这个例子:

假设您在通用上下文中工作,但您希望确保 T 的实例能够将自身序列化为流(可以是文件、字节列表),并且T 的实例可以从流中反序列化。

在写作的情况下,这很容易,因为可以假设您已经有一个实例可以使用(尽管您将无法序列化null):

public interface IStreamWritable
{
    // When called, this IStreamWritable instance
    // serializes itself to a stream.
    void Write(IStream stream);
}

...

void Write<T>(IStream stream, T t) where T : IStreamWritable
{
    t.Write(stream);
}

但是在阅读的情况下,你遇到了一个问题:

public interface IStreamReadable
{
    // When called, returns an instance 
    // deserialized from the stream.
    void Read(IStream stream);
}

...

T Read<T>(IStream stream) where T : IStreamReadable, new()
{
    var t = new T();
    t.Read(stream);
    return t;
}

这似乎可行,但它对如何实例化被反序列化的对象做出了假设。也许您想 return 现有实例而不是创建新实例?它还需要 new() 约束,这可能是不可取的。

毕竟,当您在特定实例的上下文之外工作时,在静态上下文中工作是有意义的。所以你可以试试这个:

public interface IStreamReadable
{
    // When called, returns an instance 
    // deserialized from the stream.
    static IStreamReadable Read(IStream stream);
}

...

T Read(IStream stream) where T : IStreamReadable
{
    return T.Read(stream);
}

或者,或者,为了避免装箱:

public interface IStreamReadable<T> where T : IStreamReadable<T>
{
    // When called, returns an instance 
    // deserialized from the stream.
    static T Read(IStream stream);
}

...

T Read(IStream stream) where T : IStreamReadable<T>
{
    return T.Read(stream);
}

不幸的是,两者都无法编译,因为您不能在接口中声明静态成员。但是,如果编译器允许我这样做,那将是理想的解决方案,因为它不假设您如何处理实例化,而是将责任推给接口实现者。

我找到了一个适用于结构的不错的解决方案:

public interface IFoo
{
    void Foo();
}

...

CallFoo<T>() where T : struct, IFoo
{
    return default(T).Foo();
}

IFoo 的实现者调用静态方法。当然,在这种情况下,由于 default(T) returning null,这种方法在引用类型的情况下会失败。 使用 return new T().Foo(); 也可以,但这需要再次使用 new() 约束,并丢弃 T 不必要地创建垃圾的实例。

我考虑过以某种方式使用反射作为变通方法,但我想知道是否有人想出自己的变通方法来解决他们想要分享的这个限制。

如果您将创建 IStreamReadable 对象的责任委托给 "Factory"class

,您的问题就会得到解决
using System;

namespace ConsoleApplication5
{
    public interface IStream { }
    public interface IStreamWritable { void Write(IStream stream); }
    public interface IStreamReadable { void Read(IStream stream); }
    public interface IStreamReadableFactory { IStreamReadable Create(); }

    public class InstanceFactory : IStreamReadableFactory
    {
        public IStreamReadable Create() { throw new NotImplementedException(); }
    }
    public class StaticFactory : IStreamReadableFactory
    {
        public static IStreamReadable GetInstance() { throw new NotImplementedException(); }
        IStreamReadable IStreamReadableFactory.Create() { return GetInstance(); }
    }

    public static class Program
    {
        public static void Main()
        {
            IStream stream = null;
            var s1 = Read(new StaticFactory(), stream);
            var s2 = Read(new InstanceFactory(), stream);
        }

        static IStreamReadable Read(IStreamReadableFactory factory, IStream stream)
        {
            var t = factory.Create();
            t.Read(stream);
            return t;
        }
    }
}

Suppose you are working in a generic context, but you want to be sure that instances of T are able to serialize themselves to a stream (could be a file, a list of bytes), and that instances of T can be deserialized from a stream.

我个人不关心 T 的实例是否可以反序列化 自身 ,只要它们 可以被序列化 to/from 一个流。这样做的方法不是强制 T 为这些方法提供实现(因为 class 可能有其他责任),而是强制某人提供 的实现可以.

给定界面:

public interface IStreamDeserializer<T>
{
    T Read(IStream stream);
}

...你可以这样写一个方法:

public T GetFromFile<T>(string path, IStreamDeserializer<T> deserializer)
{
    using (var stream = GetFileStream(path))
    {
        return deserializer.Read(stream);
    }
}

因此,为了调用 GetFromFile<Foo>(...),必须有人生成一个知道如何反序列化 Foo 对象的 class。他们会将这种依赖注入到你的方法中。

当然,反序列化器的存在可能不是每个实现GetFromFile()的先决条件——这是你的实现的一个方面,可能会改变与您的方法签名不同的原因。因此,您可能应该改用 构造函数注入 ,这意味着您的 class 变得通用,而不仅仅是您的方法。

public class FileEntityRetriever<T> : IFileEntityRetriever
{
    IStreamDeserializer<T> deserializer;

    public FileEntityRetriever(IStreamDeserializer<T> deserializer)
    {
        this.deserializer = deserializer;
    }

    public T GetFromFile(string path, IStreamDeserializer<T> deserializer)
    {
        using (var stream = GetFileStream(path))
        {
            return deserializer.Read(stream);
        }
    }

}