繁体   English   中英

如何从共享相同接口的对象列表中访问对象的特定属性

[英]How to access the object's specific properties from a list of objects sharing the same interface

我有一个应用程序,其中有 10 个不同类型的对象。 我希望将它们放在同一个列表中并在很多情况下迭代它们。 我不能把它们放在一个列表中,因为它们是不同的类型。 所以我创建了一个接口并创建了一个所有对象共享的属性。 现在我有对象列表,列表类型是“接口”。 当我遍历对象时,我无法访问该对象的特定属性,因为编译器只会在运行时知道它是什么对象。 因此,如果我尝试编写 Object_A.Name 代码,Visual Studio 将显示错误,因为它不知道它们的对象类型。 我显然可以做一个 if else 或类似的事情来找到对象的类型并对其进行转换,但我想知道有更好的方法,或者这个拥有接口的整个方法是否是错误的,如果我应该开始不同的方向。

在下面的代码中,我想获得 Devname,我不能,因为它不是界面的一部分,而是属于每个对象。 我可以让它成为界面的一部分,但我可能时不时地需要获得一个特定的属性。 因此想知道是否有办法做到这一点。

foreach (ICommonDeviceInterface device in Form1.deviceList)
{
if (device.DevName.Equals(partnername))
{
return device.Port[portNo].PortRef;
}
}

一种方法是使用反射尝试从对象中获取命名属性的属性值,使用辅助方法,例如:

public static object GetPropValue(object src, string propName)
{
    return src?.GetType().GetProperty(propName)?.GetValue(src, null);
}

以上代码的功劳来自:使用 C# 中的反射从字符串中获取属性值

这不需要检查类型或强制转换,它只返回属性的值,如果不包含该属性则返回null

在使用中它可能看起来像:

private static void Main()
{
    // Add three different types, which all implement the same interface, to our list
    var devices = new List<ICommonDeviceInterface>
    {
        new DeviceA {DevName = "CompanyA", Id = 1},
        new DeviceB {DevName = "CompanyB", Id = 2},
        new DeviceC {Id = 3},
    };

    var partnerName = "CompanyB";

    foreach (var device in devices)
    {
        // Try to get the "DevName" property for this object
        var devName = GetPropValue(device, "DevName");

        // See if the devName matches the partner name
        if (partnerName.Equals(devName))
        {
            Console.WriteLine($"Found a match with Id: {device.Id}");
        }
    }
}

用于上述示例的类:

interface ICommonDeviceInterface
{
    int Id { get; set; }
}

class DeviceA : ICommonDeviceInterface
{
    public int Id { get; set; }
    public string DevName { get; set; }
}

class DeviceB : ICommonDeviceInterface
{
    public int Id { get; set; }
    public string DevName { get; set; }
}

class DeviceC : ICommonDeviceInterface
{
    public int Id { get; set; }
}

使用“as”和“is”来知道什么类型的接口

public class A : ICommonDeviceInterface 
{
  public int AMember;
}
public class B :ICommonDeviceInterface 
{
  public int BMember;
}

foreach (ICommonDeviceInterface device in Form1.deviceList)
{

    if(device is A)
    {
       A a = device as A;
       a.AMember = 100;
    }
    else if(device is B)
    {
       B b = device as B;
       b.BMember = 123;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM