开发者

c#: get class member by name (reflection)

开发者 https://www.devze.com 2023-02-20 14:45 出处:网络
I have two lists (list) l1 &a开发者_高级运维mp; l2. i\'m getting from outside the name of the list i want to use (let say l1).

I have two lists (list) l1 &a开发者_高级运维mp; l2. i'm getting from outside the name of the list i want to use (let say l1).

how can i find requested list ?

do i need to use getMember method ?

thanks


You can use reflection, but it's fairly expensive. Here's a question that outlines how to do that:

C# Reflection : Finding Attributes on a Member Field

Given that the list name is known at compile time, you could consider implementing a method that accepts the string name of the list and returns a reference to the appropriate list using a switch statement or if statement.

static IList FindList(string name)
{
  if (name == "l1") { return l1; }
  else if (name == "l2") { return l2; }
  else throw Exception("List " + name + " not found.");
}

That will be faster at runtime than using reflection but requires maintenance (if you have enough lists to warrant the effort, you could code generate that method).

0

精彩评论

暂无评论...
验证码 换一张
取 消