简体   繁体   中英

How to add a "char" to variable in C#

Yo, do you guys have any idea on how to add something to variable name/id? I can't really explain that so I'll just paste my code and explain what I want to do, or maybe you have a better idea to how to resolve that.

int[] array = new int[9];
            for (int i=0; i < 9; i++)
            {
                j=i+1.ToString();
                FindViewById<Button>(Resource.Id.***Num1***).Click += (o,e)=> 
                {
                    Result.Text += "j"; 
                };          
            }    

I've got 9 buttons and all of them are numbered from 1 to 9. I wan't to create an array to avoid many lines of useless code. So the question is: how to add a number ( or a string ) to this "Num" id, so in every iteration there will be another slot of array fulled with another button click event. Is it even possible to do this this way? Thanks for an answer :>.

If you want to get a resource identifier from its name, you need to use Resources.GetIdentifier() . For example, assuming the ID of your button is Num5 :

var buttonNumber = 5;
var resourceId = Resources.GetIdentifier($"Num{buttonNumber}", nameof(Resource.Id).ToLower(), _activity.PackageName);
var button = FindViewById<Button>(resourceId);

I hope it helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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