簡體   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