0

我有这些类和接口:

public class XContainer
{
    public List<IXAttribute> Attributes { get; set; }
}

public interface IXAttribute
{
    string Name { get; set; }
}

public interface IXAttribute<T> : IXAttribute
{
    T Value { get; set; }
}

public class XAttribute<T> : IXAttribute<T>
{
    public T Value { get; set; }
}

我需要迭代 XContainer.Attributes并获取属性Value,但我需要转换IXAttribute为更正通用表示,例如XAttribute<string>orXAttribute<int>但我不想使用 if-else if-else 语句来检查它,例如 if XContainerl.Attributes[0] is XAttribute<string>then cast ...

这里有更好的方法吗?

4

2 回答 2

1

有更好的方法来做到这一点。

假设您保留当前的整体设计,您可以更改您的非通用接口和实现,如下所示:

public interface IXAttribute
{
    string Name { get; set; }
    object GetValue();
}

public class XAttribute<T> : IXAttribute<T>
{
    public T Value { get; set; }

    public object GetValue()
    {
       return Value;
    }
}

然后你的迭代器就可以访问GetValue(),不需要强制转换。

也就是说,我认为该设计可能不适合您正在做的事情。

于 2012-06-02T15:01:51.980 回答
0

您还可以定义通用扩展方法

public static class XAttributeExtensions
{
    public T GetValueOrDefault<T>(this IXAttribute attr)
    {        
        var typedAttr = attr as IXAttribute<T>;
        if (typedAttr == null) {
            return default(T);
        }
        return typedAttr.Value;
    }
}

然后你可以用(假设Tint)调用它

int value = myAttr.GetValueOrDefault<int>();

将其实现为扩展方法的原因是它可以与非通用接口的任何实现一起使用IXAttribute

于 2012-06-02T15:20:10.683 回答