Can we use the value of GetType().ToString() as an identifier to get an object?

StackOverflow https://stackoverflow.com/questions/21854485

  •  13-10-2022
  •  | 
  •  

سؤال

Hi I have an object new Sword() derived from abstract class Item. Can I somehow use a string property Name or this.GetType().ToString() as identifier to refer to a constant object from another class(static). I wan to refer to a bitmap image provided as System.Drawing.Bitmap object from another static class. Here is code I have:

Basically:

//WORKS
return HeroesPrototype.mapConsts.Bitmaps.sword;
//NOT WORKS 
string Name="sword";
return HeroesPrototype.mapConsts.Bitmaps.<string Name>;    

//More in details:  
abstract class Item:Drawable//class Item will serve as parent for all items(axe,sword, staff etc.) in this case new Sword()
{
    public string  Name { get; set; }//property that I wish to use for identifier
    Bitmap Drawable.GetSprite()//method from Drawable interface that I wish to inherit for all types of item
    {
        return HeroesPrototype.mapConsts.Bitmaps.<string Name>;//Name="sword" is my object identifier
    }
}
namespace HeroesPrototype.mapConsts
{
    public static class Bitmaps
    {
        public static System.Drawing.Bitmap castle = new System.Drawing.Bitmap(Bitmap.FromFile(@"..\..\sprites\mapobj\sword.png"));
    }
}
هل كانت مفيدة؟

المحلول

if i understand right you need use GetField and GetValue something like this

Bitmap Drawable.GetSprite()
{
    return (Bitmap)(typeof(HeroesPrototype.mapConsts.Bitmaps)
                   .GetField(Name)
                   .GetValue(null));
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top