0

嗨,我需要通过属性名称获取 BindableProperty。 在此处输入图像描述

public BindableProperty GetBindableProperty(BindableObject bindableObj, string propertyName) {
    if(typeof(Entry) == bindableObj.GetType()) {
        if("Text" == propertyName) {
            return (Entry.TextProperty);
        }
        if("TextColor" == propertyName) {
            return (Entry.TextColorProperty);
        }
    }
    return (null);
}

但我不想使用这种“if else”风格。有没有不需要判断类型和名称的通用方法?

4

1 回答 1

0

嗨,我现在找到了解决方案:

public BindableProperty GetBindableProperty(BindableObject bindableObj, string propertyName) {
    Type type = bindableObj.GetType();
    FieldInfo fieldInfo;
    while(null == (fieldInfo = type.GetField(propertyName + "Property", BindingFlags.Static | BindingFlags.Public))) {
        type = type.BaseType;
    }
    if(null == fieldInfo) {
        throw (new Exception("Can not find the BindableProperty for " + propertyName));
    }
    return ((BindableProperty)(fieldInfo.GetValue(bindableObj)));
}
于 2020-02-14T08:11:06.657 回答