dynamic acces to class variables?
-
Is there any possiblities to access all of the variables from a class dynamically (something like MyFriends.GetVariable("Name"); )? fsadfasdfsadfasdfasdf
-
Is there any possiblities to access all of the variables from a class dynamically (something like MyFriends.GetVariable("Name"); )? fsadfasdfsadfasdfasdf
You can use reflection to enumerate types and their members (properties, fields, and methods). Read Discovering Type Information at Runtime[^] in the .NET Framework SDK. Note that these aren't "variables". Variables - in practically any language - are temporary memory addresses to store information in a particular function or method (methods are functions declared for a class or other structure). You can also have global variables. To enumerate properties on a class, for example (since you typically shouldn't expose fields publicly; you have little control over what gets assigned and can't validate the data):
using System;
using System.Reflection;
class Person
{
static void Main()
{
Person p = new Person("Heath", DateTime.Parse("08/07/1978"));
Reflect(p);
}
static void Reflect(Person p)
{
PropertyInfo[] props = p.GetType().GetProperties(
BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
if (props != null)
{
foreach (PropertyInfo prop in props)
{
object value = prop.GetValue(p, null);
Console.WriteLine("{0} ({1}) = {2}", prop.Name, prop.PropertyType,
value);
}
}
}
Person(string name, DateTime birthday)
{
this.name = name;
this.birthday = birthday;
}
string name;
DateTime birthday;
public string Name
{
get { return name; }
set
{
if (value == null) throw new ArgumentNullException();
name = value;
}
}
public DateTime Birthday
{
get { return birthday; }
set { birthday = value; }
}
}This posting is provided "AS IS" with no warranties, and confers no rights. Software Design Engineer Developer Division Sustained Engineering Microsoft [My Articles] [My Blog]
-
And is there some Information available for Regexps in C#? I wasn't able to extract strings out of an other string with Regex.Match (e.g. /^([^=]+)=(.+)$/ - should extract key and value of a "key=value" pair...) (I just edited my account options)