Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
String to reference static object
Message
From
15/12/2009 10:19:20
 
 
General information
Forum:
ASP.NET
Category:
Coding, syntax and commands
Environment versions
Environment:
C# 3.0
Miscellaneous
Thread ID:
01439141
Message ID:
01439157
Views:
32
>>>I think I'm having a pre-lunch mental block. Simple case: Class:
>>>public class LLCommands
>>>{
>>>      private static RoutedUICommand lockDown;
>>>
>>>      static LLCommands()
>>>      { lockDown = new RoutedUICommand("LockDown","LockDown",typeof(LLCommands));   }
>>>
>>>      public static RoutedUICommand LockDown
>>>      {  get {return lockDown; } }
>>>}
elsewhere:
List<RoutedUICommands>() SupportedCommands;
>>>SupportedCommands.Add(LLCommands.LockDown);
So far, so good. But how can I achieve the add given only a string (e.g "LLCommands.LockDown") ?
>>
>>Sorry - can't test - much to my regret
>>
>>That would be reflection I think
>
>This works (but maybe there's a shorter way?):
Type t = typeof(LLCommands);
>            PropertyInfo p =  t.GetProperty("LockDown", BindingFlags.Public | BindingFlags.Static);
>            RoutedUICommand r = (RoutedUICommand) p.GetValue(LLCommands.LockDown,null);
>            SupportedCommands.Add(r);
>obviously needs a bit of exception handling tho.....

That was basically what I was thinking

Exception Handling : Yes
You could write a 'TryEval' method - cons (1) a lot slower and (2) compiler cannot catch (your) typing errors
Gregory
Previous
Next
Reply
Map
View

Click here to load this message in the networking platform