Accessing object properties from string representations
In actionscript an object's property can be accesses in this way:
object["propertyname"]
Is so开发者_开发知识库mething like this possible in c#, without using reflection?
No, you have to use reflection.
If could at most create an helper extension method like in this example:
using System;
static class Utils {
public static T GetProperty<T>(this object obj, string name) {
var property = obj.GetType().GetProperty(name);
if (null == property || !property.CanRead) {
throw new ArgumentException("Invalid property name");
}
return (T)property.GetGetMethod().Invoke(obj, new object[] { });
}
}
class X {
public string A { get; set; }
public int B { get; set; }
}
class Program {
static void Main(string[] args) {
X x = new X() { A = "test", B = 3 };
string a = x.GetProperty<string>("A");
int b = x.GetProperty<int>("B");
}
}
This is not good, however.
First because you are turning compile-time errors in runtime errors.
Second, the performance hit from reflection is unjustified in this case.
I think that the best advice here is that you should not try to program in C# as if it was ActionScript.
You can define indexer in your class:
public class IndexerTest
{
private Dicionary<string, string> keyValues = new ...
public string this[string key]
{
get { return keyValues[key]; }
set { keyValues[key] = value; }
}
}
And use it like this:
string property = indexerTest["propertyName"];
精彩评论