我有这个代码
public class ParameterOrderInFunction : Attribute
{
public int ParameterOrder { get; set; }
public ParameterOrderInFunction(int parameterOrder)
{
this.ParameterOrder = parameterOrder;
}
}
public interface IGetKeyParameters
{
}
public class Person: IGetKeyParameters
{
[ParameterOrderInFunction(4)]
public string Age { get; set; }
public string Name { get; set; }
[ParameterOrderInFunction(3)]
public string Address { get; set; }
[ParameterOrderInFunction(2)]
public string Language { get; set; }
[ParameterOrderInFunction(1)]
public string City { get; set; }
public string Country { get; set; }
}
class Program
{
static void Main(string[] args)
{
Person person = new Person();
person.Address = "my address";
person.Age = "32";
person.City = "my city";
person.Country = "my country";
Test t = new Test();
string result = t.GetParameter(person);
//string result = person.GetParameter();
Console.ReadKey();
}
}
public class Test
{
public string GetParameter(IGetKeyParameters obj)
{
string[] objectProperties = obj.GetType()
.GetProperties()
.Where(p => Attribute.IsDefined(p, typeof(ParameterOrderInFunction)))
.Select(p => new
{
Attribute = (ParameterOrderInFunction)Attribute.GetCustomAttribute(p, typeof(ParameterOrderInFunction), true),
PropertyValue = p.GetValue(this) == null ? string.Empty : p.GetValue(this).ToString()
})
.OrderBy(p => p.Attribute.ParameterOrder)
.Select(p => p.PropertyValue)
.ToArray();
string keyParameters = string.Join(string.Empty, objectProperties);
return keyParameters;
}
}
我想做的是以某种顺序将属性值作为一个字符串获取。
如果我将函数 GetParameter 放在 Person 类中,它就可以正常工作。 但是,我也想将函数 GetParameter 与其他类一起使用, 所以我创建了空界面。 现在我希望每个 IGetKeyParameters 类型的对象都可以使用该函数。 但我在行中遇到异常:
PropertyValue = p.GetValue(this) == null ? string.Empty : p.GetValue(this).ToString()
最佳答案
您应该将加载属性从 this
(没有此类属性)更改为参数对象:
PropertyValue = p.GetValue(obj) == null ? string.Empty : p.GetValue(obj).ToString()
关于c# - 对象属性的反射(reflect),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42435513/