Скажем, у меня есть класс B, определенный следующим образом:
public class B
{
public int Id { get; set; }
}
Тогда вы можете получить значение идентификатора, как это:
var b = new B();
b.Id = 60;
int id = GetId(b);
с определенным методом GetId
следующим образом:
public static int GetId(object o)
{
var idProperty = o.GetType().GetProperties().FirstOrDefault(p => p.Name == "Id");
if (idProperty == null)
throw new ArgumentException("object does not have an Id property", "o");
if (idProperty.PropertyType.FullName != typeof(Int32).FullName)
throw new ArgumentException("object has an Id property, but it is not of type Int32", "o");
return (int)idProperty.GetValue(o, new object[] { });
}
Более общим решением было бы создать метод, подобный этому:
public static T GetProperty<T>(object o, string propertyName)
{
var theProperty = o.GetType().GetProperties().FirstOrDefault(p => p.Name == propertyName);
if (theProperty == null)
throw new ArgumentException("object does not have an " + propertyName + " property", "o");
if (theProperty.PropertyType.FullName != typeof(T).FullName)
throw new ArgumentException("object has an Id property, but it is not of type " + typeof(T).FullName, "o");
return (T)theProperty.GetValue(o, new object[] { });
}
, который будет вызываться так:
var b = new B();
b.Id = 60;
int id = GetProperty<int>(b, "Id");