簡體   English   中英

如何在C#中動態引用遞增的屬性?

[英]How do I dynamically reference incremented properties in C#?

我有稱為reel1,reel2,reel3和reel4的屬性。 如何通過將整數(1-4)傳遞給我的方法來動態引用這些屬性?

具體來說,我正在尋找如何在不知道對象名稱的情況下獲取對象引用。

在Javascript中,我會這樣做:

temp = eval("reel" + tempInt);

和temp將等於reel1,即對象。

似乎無法在C#中找出這個簡單的概念。

這通常是C#中避免的。 通常還有其他更好的選擇。

話雖這么說,你可以使用Reflection來獲取像這樣的屬性的值:

object temp = this.GetType().GetProperty("reel" + tempInt.ToString()).GetValue(this, null);

但是,更好的選擇可能是在您的類上使用Indexed Property ,這將允許您執行this[tempInt]

您可以使用PropertyInfo通過包含屬性名稱的字符串訪問屬性值。

例:

PropertyInfo pinfo = this.GetType().GetProperty("reel" + i.ToString());
return (int)pinfo.GetValue(this, null);

嘗試此鏈接獲取屬性的相應PropertyInfo對象,然后使用GetValue將其傳遞給您要評估屬性的實例

這是你可以用像javascript這樣的解釋語言來解決的問題之一,在C#等編譯語言中非常困難。 最好采取另一種策略:

switch(tempInt)
{
    case 1:
       temp = reel1;
       break;
    case 2:
       temp = reel2;
       break;
    case 3:
       temp = reel3;
       break;
}

使用InvokeMember和BindingFlags.GetProperty。 您必須具有對“擁有”對象的引用,並且您必須知道要檢索的屬性的類型。

namespace Cheeso.Toys
{
    public class Object1
    {
        public int Value1 { get; set; }
        public int Value2 { get; set; }
        public Object2 Value3 { get; set; }
    }

    public class Object2
    {
        public int Value1 { get; set; }
        public int Value2 { get; set; }
        public int Value3 { get; set; }
        public override String ToString()
        {
            return String.Format("Object2[{0},{1},{2}]", Value1, Value2, Value3);
        }
    }

    public class ReflectionInvokePropertyOnType
    {

        public static void Main(string[] args)
        {
            try
            {
                Object1 target = new Object1
                    {
                        Value1 = 10, Value2 = 20, Value3 = new Object2
                            {
                                Value1 = 100, Value2 = 200, Value3 = 300
                            }
                    };

                System.Type t= target.GetType();

                String propertyName = "Value3";

                Object2 child = (Object2) t.InvokeMember (propertyName,
                                                          System.Reflection.BindingFlags.Public |
                                                          System.Reflection.BindingFlags.Instance  |
                                                          System.Reflection.BindingFlags.GetProperty,
                                                          null, target, new object [] {});
                Console.WriteLine("child: {0}", child);
            }
            catch (System.Exception exc1)
            {
                Console.WriteLine("Exception: {0}", exc1.ToString());
            }
        }
    }
}

暫無
暫無

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

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