通用类工厂问题

Vad*_*dim 5 c# oop

贝娄是我的代码的简化版本:

public interface IControl<T>
{
    T Value { get; }
}

public class BoolControl : IControl<bool>
{
    public bool Value
    {
        get { return true; }
    }
}

public class StringControl : IControl<string>
{
    public string Value
    {
        get { return ""; }
    }
}
public class ControlFactory
{
    public IControl GetControl(string controlType)
    {
        switch (controlType)
        {
            case "Bool":
                return new BoolControl();
            case "String":
                return new StringControl();
        }
        return null;
    }
}
Run Code Online (Sandbox Code Playgroud)

问题出在ControlFactory类的GetControl方法中.因为它返回IControl而我只有IControl <T>这是一个通用接口.我不能提供T,因为在Bool情况下它会bool而在String情况下它将是字符串.

知道我需要做些什么来使它工作?

Dan*_*ner 5

只是衍生IControl<T>IControl.

public interface IControl<T> : IControl
{
    T Value { get; }
}
Run Code Online (Sandbox Code Playgroud)

UPDATE

如果我错过了您的理解,并且您不想要非通用接口,那么您也必须使该方法GetControl()通用.

public IControl<T> GetControl<T>()
{
    if (typeof(T) == typeof(Boolean))
    {
        return new BoolControl(); // Will not compile.
    }
    else if (typeof(T) == typeof(String))
    {
        return new StringControl(); // Will not compile.
    }
    else
    {
        return null;
    }
}
Run Code Online (Sandbox Code Playgroud)

现在您遇到的问题是新控件无法隐式转换为IControl<T>您必须将其显式化.

public IControl<T> GetControl<T>()
{
    if (typeof(T) == typeof(Boolean))
    {
        return new (IControl<T>)BoolControl();
    }
    else if (typeof(T) == typeof(String))
    {
        return (IControl<T>)new StringControl();
    }
    else
    {
        return null;
    }
}
Run Code Online (Sandbox Code Playgroud)

UPDATE

将演员表as IControl<T>改为(IControl<T>).这是首选,因为如果在as IControl<T>静默返回时存在错误,它将导致异常null.