使用泛型时 C# 比较属性类型。带有反思
我有一些嵌套的泛型类,我想通过反射检索实际的属性类型以实现一些自定义逻辑。
public class Base<T>
public Base(T model)
{
this.model = model;
}
public void AMethod(){
foreach (var property in this.model.GetType().GetProperties())
{
if(property.Name = "Test") {
...retrieve type }
}
}
}
我现在有一个带有 Test 属性的通用 BaseModel,它再次使用通用类型,并
BaseModel<T>
{
public int Id {get; set;}
public string Name {get; set;}
public MyClass<T> Test {get; set;}
}
FirstModel: BaseModel<float>{}
SecondModel: BaseModel<int>{}
从 AMethod 定义了两个派生类,如果 Test 属性是类型,我想基于模型检索基础 Myclass 以通用方式(如果可能),稍后又是 T 的特定类型,以根据类型(MyClass 或 MyClass)切换操作。
<============================>更新<============================>
我刚刚在 Fiddle 中创建了一个测试用例。类和继承的结构可能很复杂。目的是向用户公开一个简单的类来实例化不同的对象“Floatinputs”、“FloatInputsSpecial”、“IntegerInputs”。所有这些都源自 Base,其中 T 是特定模型。该模型可以具有或不具有 MyObject 类型的测试属性。 我想从基类构造函数访问此类型。
谢谢
I have some generic class nested and I would like to retrieve with reflection the actual property type to implement some custom logic.
public class Base<T>
public Base(T model)
{
this.model = model;
}
public void AMethod(){
foreach (var property in this.model.GetType().GetProperties())
{
if(property.Name = "Test") {
...retrieve type }
}
}
}
I have now a generic BaseModel with a Test property that use again the Generic type and are defined two derived class
BaseModel<T>
{
public int Id {get; set;}
public string Name {get; set;}
public MyClass<T> Test {get; set;}
}
FirstModel: BaseModel<float>{}
SecondModel: BaseModel<int>{}
From the AMethod I would like to retrieve base on model if Test property is of type
Myclass in a generic way (if possible) and also later on which is the specific type of T to switch operations based on type (MyClass or MyClass).
<===========================> UPDATE <===========================>
I've just created a test case in Fiddle. The structure of the class and inheritance could be complex. The purpose is to have a simple class exposed to the user to instantiate different Objects 'Floatinputs','FloatInputsSpecial', 'IntegerInputs'. All these derives from Base where T is a specific model. This Model can have or not a Test Property of Type MyObject.
From the Base class constructor I would like to access this type.
Thank you
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论