簡體   English   中英

通用類工廠問題

[英]Generic class factory problem

貝婁是我的代碼的簡化版本:

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

問題出在ControlFactory類的GetControl方法中。 因為它返回IControl而我只有IControl <T>這是一個通用接口。 我不能提供T,因為在Bool情況下它會bool而在String情況下它將是字符串。

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

只需從IControl派生IControl<T>

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

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

現在您遇到的問題是新控件無法隱式轉換為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>as IControl<T>更改為(IControl<T>) 這是首選,因為如果存在錯誤,它將導致異常,而as IControl<T>靜默返回null

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>();

返回類型必須是通用的,因為它確實是。 想想你將如何使用它。 返回強類型對象不需要通用工廠方法。

即使你能做到,也會有什么好處

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

或者,那個可行的,

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

特定的

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

無論哪種方式,您在客戶端都有switch()。 返回一個對象,或者有一個非類型的IControl接口。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM