是否可以访问一个接口字典中的多个接口



首先:对不起,如果问题是奇怪的措辞。我是C#中的多类新手,我有些困扰。

我目前正在制作一个库存系统,该系统使用一个字典为所有项目。这些项目本身是不同的类,并将界面用于属性。假设这些是界面,为简单起见。一个接口具有名称,第二个接口具有特定值,第三个接口具有另一个特定值。

我似乎无法弄清楚(如果可能的话(我可以访问第二个接口的属性,因为我唯一得到的建议是字典中使用的itemType的建议。

// the interface examples
interface IStandardProperties
{
   string Name { get; set; } 
}
interface IItemType1
{ 
    int SomeValue { get; set; } 
}
interface IItemType2
{ 
    int AnotherValue { get; set; } 
}
// Then we have two classes that uses these. 
class ItemType1 : IStandardProperties, IItemType1
{ 
    public string Name; 
    public int SomeValue;
    public ItemType1() 
    {
       this.Name = "Item type 1"; this.SomeValue = "10";
    }
}
class ItemType2 : IStandardProperties, IItemtype2
{
    public string Name; 
    public int SomeValue;
    public ItemType1() 
    { 
        this.Name = "Item type 1"; 
        this.AnotherValue = "100";
    }
}
// and finally the dictionary in question.
Dictionary<int, IStandardProperties> items = New Dictionary<int, IStandardProperties>();

现在,这两个项目都可以存储在字典中,但是我似乎无法弄清楚如何(或者如果可能的话(访问通过词典的" valuue"和其他值的接口属性中存储的值。我已经看到了几个示例,其中使用了" InterfaceName",但我不确定此示例。

是否有一种访问这些方法?(,如果我对界面有可怕的误解,这些值甚至存储在字典中?((

我都不是专家,所以我希望您在此问题上可以提供任何更正或帮助。

创建Dictionary<int, IStandardProperties>时,我们唯一知道的是每个项目都实现了特定的接口。

如果您要询问ItemType1类型的AnotherValue属性,那么您显然不会做正确的事情。这就是为什么您的字典项目无法显示此属性的原因:它们不是字典的每个元素的属性

您可以实现想要的方法是类型检查:

if (items[0] is IItemType1) {
    (items[0] as IItemType1).SomeValue ... 
} 
if (items[0] is IItemType2) {
    (items[0] as IItemType2).AnotherValue ... 
}

这将检查该项目是否实现了上述接口,然后访问该接口的成员(属性(

如果我正确理解您的问题,则此行

class ItemType1 : IStandardProperties, IItemType1

ItemType1声明为实现IStandardPropertiesIItemType1,这意味着它具有特征。

您的dicationary声明

Dictionary<int, IStandardProperties> items = New Dictionary<int, IStandardProperties>();

说您的字典是从 intIStandardProperties键入的。这意味着字典的值为已知 oberced 是类型IStandardProperties。但是,这无法说明您的价值的可能特征。

因此,您必须在需要时要求特定特征(请注意,从C#7开始有快捷方式,我故意避免使用(:

IStandardProperties v; 
if (items.TryGetValue("key", out v))
{
    // found. the line below asks if the interface is supported
    var item1 = v as IItemType1;
    if (item1 != null)
    {
        // v supports IItemType1, therefore you can do something with it, by using item1
    }
    // we repeat for IItemType2
    var item2 = v as IItemType2;
    if (item2 != null)
    {
        // v supports IItemType2, therefore you can do something with it, by using item2
    }
}
else
{
    // not found
}

最新更新