0

I have an object named 'Account' and the following code:

Account objAcc = new Account();
objAcc.Name = "Test";

The above is working fine, as expected. I now have a list of values as follows:

string props = "Name,Address,Telephone";

Now, what I want to do is see if "Name" exists in that list. I only have the object to use though (hard coding a case statement etc isn't possible as the object is dynamic), so from objAcc.Name, I somehow need to get "Name" from that, and then see if it's in the list.

Thanks in advance, I hope it's clear enough,

Dave

4

2 回答 2

2

您可以通过这样做来使用反射:

var properties = objAcc.GetType().GetProperties();
foreach(var property in properties)
{
  if(props.Contains(property.Name))
  {
     //Do you stuff
  }
}
于 2013-07-25T10:05:17.543 回答
1
string test = objAcc.GetType().GetProperty("Name") == null ? "" : objAcc.GetType().GetProperty("Name").Name;
bool result = "Name,Address,Telephone".Split(',').Contains(test);

如果您愿意,可以使用以下方法:

public bool PropertyExists<T>(string propertyName, IEnumerable<string> propertyList,T obj)
{
    string test = obj.GetType().GetProperty(propertyName) == null ? "" : obj.GetType().GetProperty(propertyName).Name;
    bool result = propertyList.Contains(test);
    return result;
}

扬尼斯

于 2013-07-25T10:10:39.500 回答