簡體   English   中英

通過包含對象名稱的指定部分的字符串(或整數)引用對象的屬性 - C#

[英]Reference an object's property by a string (or integer) that contains specified part of the object's name - C#

例如,我有一個方法返回值“4”...我的按鈕的名稱是“ b4 ”。 我希望取決於方法返回的數字來更改b “X”的Text屬性。 最簡單的方法在C#中做到這一點。 我是初學者,所以請解釋一下......我知道這可能是一個重復的帖子。 但我不明白所有類似帖子中的答案。 代碼的布局是這樣的:

我有一個包含五個數字的數組(例如“int [] rnum = {1,6,7,3,8}”)...我還有5個按鈕應該被禁用,具體取決於數組中給出的整數...我有25個按鈕,它們的名字如下“b1,b2,b3,b4 ......等”。 那么通過使用數組中給出的整數引用按鈕對象的名稱來更改按鈕的“啟用”屬性的最簡單方法是什么?例如,rnum [1] = 6 ==> b6.Enabled = false ...我知道我可以做一個switch語句但是如果有很多按鈕我怎么能自動化呢?

正如@Alex K.所說

public Button GetButtonByIndex(int index)
{
  return (Button)this.Controls.Find("b" + index, true).FirstOrDefault();
}

那么GetButtonByIndex(1)將返回b1等。

你可以用反射來做。 這是一個例子:

class Foo
{
    public int Bar1 { get; set; }
    public int Bar2 { get; set; }
    public Foo()
    {
        Bar1 = 2;
        Bar2 = 3;
    }
    public int GetBar(int barNum) //return type should be Button for you
    {
        PropertyInfo i = this.GetType().GetProperty("Bar"+barNum);
        if (i == null)
            throw new Exception("Bar" + barNum + " does not exist");
        return (int)i.GetValue(this); //you should cast to Button instead of int
    }
}

和主要:

class Program
{
    static void Main(string[] args)
    {
        Foo f = new Foo();
        for (int i = 1; i <= 3; i++)
            try
            {
                Console.WriteLine(f.GetBar(i));
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        Console.ReadLine();
    }
}

輸出將是:

2
3
Bar3 does not exist

請注意,雖然我打印了foo.GetBar(i)的結果,但在你的情況下你可以這樣做: foo.GetButton(i).Enabled = false;

雖然查找Controls內的Controls (遞歸或已知容器)將起作用,但更容易解決(一般)是這樣

var buttons = new[] {b1, b2, b3, b4, b5 }; // can be a field initialized in form constructor
buttons[number - 1].Text = "lalala"; // number is from 1 to 5

如果您不想將接收到的number轉換為index ,則可以將null作為第一個元素添加到數組中。

暫無
暫無

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

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