The problem with the general factory class

Bellow is a simplified version of the code I have:

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;
    }
}

The problem is the GetControl method of the ControlFactory class. Because it returns IControl, and I only have IControl <T>, which is a common interface. I cannot provide T, because in the case of Bool it will be bool, and in the case of String it will be a string.

Any idea what I need to make it work?

+5
source share
3 answers

Just deduce IControl<T>from IControl.

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

UPDATE

If I missed you and you do not need a non-common interface, you will also have to use the method 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;
    }
}

, 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;
    }
}

UPDATE

as IControl<T> (IControl<T>). , , , as IControl<T> null.

+5
public IControl<T> GetControl<T>()
{
    switch (typeof(T).Name)
    {
        case "Bool":
            return (IControl<T>) new BoolControl();
        case "String":
            return (IControl<T>) new StringControl();
    }
    return null;
}

; . , :

IControl<bool> boolControl = GetControl<bool>();
+3

, , , . , . factory.

,

IControl<bool> boolControl = controlFactory.GetControl("bool");

, ,

IControl<bool> boolControl = controlFactory.GetControl<bool>("bool");

IControl<bool> boolControl = controlFactory.GetBoolControl("bool");

() . , IControl.

0

All Articles