使用泛型输入安全性:检查T到接口<t> </t>

时间:2014-11-28 01:05:17

标签: c# generics

我想知道是否有更简单的方法来验证接口的泛型类型是否等同于传递的参数类型,最好不要特别注明类型。

我也担心我会过度设计我的设置。这可能看起来很愚蠢,因为这总体上很小。但我想要做的是在一个类(Test)之间创建一些分隔,它声明一个Order的顺序和格式。我希望能够轻松切换出我的ITransport。我希望调用者传递它希望传输使用的格式化程序的类型,但是传输应该最终说明是否创建/使用了格式化程序。

public interface IFormatter<T>
{
    void Format(T val);
}

public interface ITransport
{
    //What I can do
    void Insert<T, T1>(T val) where T1 : IFormatter<T>, new();

    //Closer to what I want
    void Insert<T>(T1 val) where T : IFormatter<T1>, new();
}

public class NumericFormatter : IFormatter<string>, IFormatter<int>
{
    public void Format(string val){ ... }
    public void Format(int val){ ... }
}

public class TestTransport : ITransport
{
    public void Insert<T, T1>(T val) where T1 : IFormatter<T>, new() { ... }
}

public class Test
{
    public Test()
    {
        int i = 1234;
        string s = "1234"
        decimal d = 1234;

        var gw = new TestTransport();

        //What I currently can do
        gw.Insert<string, NumericFormatter>(s);
        gw.Insert<int, NumericFormatter>(i);
        gw.Insert<decimal, NumericFormatter>(d); //Illegal - Compile Error

        //What I think I want
        gw.Insert<NumericFormatter>(i);
        gw.Insert<NumericFormatter>(s);
        gw.Insert<NumericFormatter>(d); //Compile error
    }
}

修改

实际上需要编译错误。我希望系统阻止开发人员使用格式化程序不知道如何处理给定类型的类型。

我的问题是:有没有办法摆脱在插入函数中明确定义类型的需要

即 -

Insert<iFormatter<T>>(T val) 

重要

Insert<T, iFormatter<T>>(T val);

我意识到我可能只是过于挑剔。

2 个答案:

答案 0 :(得分:1)

这对你有用吗?

public void Insert<T>(T value, IFormatter<T> instance)

它的作用只是让你分配一个类型,当你传递Formatter实例时,它必须符合类型。

或者你为什么不改变你的逻辑,传递你的价值类型,你总是确定IFormatter符合传递的值的类型,而不是使值符合IFormatter

更新1:

您还可以在参数

中传递包装对象
public void Insert<T>(YourWrap<T> instance);

    public class YourWrap<T>
    {
        public IFormatter<T> Formatter { get; set; }

        public T Parameter { get; set; }
    }

答案 1 :(得分:0)

如果我理解你......不应该替换这一行:

public void Insert<T, T1>(T val) where T1 : IFormatter<T>, new() { ... }

用这个:

public void Insert<T1>(T val) where T1 : IFormatter<T>, new() { ... }