Autor Beitrag
paul.-b
ontopic starontopic starontopic starontopic starontopic starontopic starontopic starontopic star
Beiträge: 26



BeitragVerfasst: Do 03.12.09 00:26 
Hallo,

Also, ich habe eine Methode, die bekommt irgendein Objekt und zwei Strings übergeben.
z.b. sowas
SetFooValue(Object foo, String Variable, String Wert)

Also "foo" hat ein Attribut, dass genau so heißt wie der Inhalt des Strings "Variable".

Ihr ahnt es schon, ich möchte diesem den String "Wert" zuweisen.

Meine Frage ist, ob sowas in C# geht?

Danke
Paul
Christian S.
ontopic starontopic starontopic starontopic starontopic starontopic starhalf ontopic starofftopic star
Beiträge: 20451
Erhaltene Danke: 2264

Win 10
C# (VS 2019)
BeitragVerfasst: Do 03.12.09 00:33 
Hallo!

Ja, das geht. Das Stichwort nennt sich Reflection. Sollte mit Bedacht eingesetzt werden, weil es recht langsam ist.

ausblenden C#-Quelltext
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
    class Blubb
    {
        public string Foo;
    }


    class Program
    {
        static void Main(string[] args)
        {
            var b = new Blubb();

            SetField(b, "Foo""Bar");

            Console.WriteLine(b.Foo);
            Console.ReadLine();
        }

        static void SetField(object o, string field, string value)
        {
            var t = o.GetType();

            var fieldInfo = t.GetField(field);
            if (fieldInfo == null)
                throw new Exception("Feld jibbet nisch");

            fieldInfo.SetValue(o, value);
        }
    }


Grüße
Christian

P.S.: "Attribute" sind in .NET was anderes, ich nahm einfach mal an, dass Du ein Feld meintest. Die sollte man übrigens eigentlich nicht public machen, sondern nur über Properties veröffentlichen.

_________________
Zwei Worte werden Dir im Leben viele Türen öffnen - "ziehen" und "drücken".
paul.-b Threadstarter
ontopic starontopic starontopic starontopic starontopic starontopic starontopic starontopic star
Beiträge: 26



BeitragVerfasst: Do 03.12.09 01:58 
saubere Antwort.
Vielen Dank!