我声明了以下接口:
public interface IDemoInterface
{
bool DemoBooleanProperty { get; set; }
string DemoStringProperty { get; set; }
IContainer RestrictiveContent { get; set; }
}为此,我实现了一种基于属性类型使用反射构建某些UI控件的方法。
public void BuildUiControls<T>(T instance, bool groupData = false)
{
foreach (var propertyInfo in instance.GetType().GetProperties())
{
if (propertyInfo.PropertyType == typeof(bool))
{
...
}
if (propertyInfo.PropertyType == typeof(string))
{
...
}
if (propertyInfo.PropertyType.IsEnum)
{
...
}
if (propertyInfo.PropertyType == typeof(IContainer))
{
BuildUiControls(???, true);
}
}
}我成功地为第一个ifs构建了控件,但是现在我想递归地使用这个函数来以相同的方式构建控件,但现在使用的是IContainer接口,它是初始接口的一个成员,而且似乎无法计算出应该传递给BuildUIControls方法的内容,以便从这个接口访问属性。
public interface IContainer
{
TestEnum MandatoryEnum { get; set; }
bool ReadOnly1Prop { get; set; }
bool ReadOnly2Prop { get; set; }
}在该方法的第一次调用中,我传递如下数据
_demoInterface = new DemoInterfaceImplementation
{
DemoBooleanProperty2 = true,
DemoStringProperty = "testString",
RestrictiveContent = new ContainerInterfaceImplementation
{
MandatoryEnum = TestEnum.One, ReadOnly1Prop = true, ReadOnly2Prop = true
}
};
vm.BuildUiControls(_demoInterface);其中_demoInterface被声明为IDemoInterface。
谢谢你的帮助!
发布于 2020-09-03 14:12:40
以下是有关的守则:
if (propertyInfo.PropertyType == typeof(IContainer))
{
BuildUiControls(???, true);
}您需要做的是获取该属性的值,然后可以使用该值递归调用您的方法。例如:
if (propertyInfo.PropertyType == typeof(IContainer))
{
var containerValue = propertyInfo.GetValue(instance) as IContainer;
BuildUiControls(containerValue);
}https://stackoverflow.com/questions/63724785
复制相似问题