C# 如何从通用用户控件获取类型和值?

C# 如何从通用用户控件获取类型和值?,c#,C#,我有一个通用用户控件: public partial class SearchBoxGeneric<T> : UserControl where T : class { private T value; public virtual T Value { get {return this.value;} set {set this.value = value} } } 但是如何获取通用用户控件的值呢?要获取Searc

我有一个通用用户控件:

public partial class SearchBoxGeneric<T> : UserControl where T : class
{
    private T value;

    public virtual T Value
    { 
        get {return this.value;}
        set {set this.value = value}
    }
}

但是如何获取通用用户控件的值呢?

要获取
SearchBoxGeneric
的所有实例,您可以使用:

this.Controls.Where(c => c.GetType().BaseType == typeof(SearchBoxGeneric<>).BaseType)
等等。

您可以使用另一个答案中的方法来确定控件是否继承自
SearchBoxGeneric

然后您可以通过反射获得

if (IsSubclassOfRawGeneric(typeof(SearchBoxGeneric<>), c.GetType()))
{
    var prop = c.GetType().GetProperty("Value");
    object value = prop.GetValue(c);
    Console.WriteLine(value);
}

这里有很多糟糕的设计:从UserControl派生,即泛型,而不是通过使其抽象并使用字符串比较类型来强制该属性。你应该想一个更好的办法。
var stringBoxes = this.Controls.OfType<SearchBoxGeneric<string>>()
var intBoxes = this.Controls.OfType<SearchBoxGeneric<int>>()
static bool IsSubclassOfRawGeneric(Type generic, Type toCheck) {
    while (toCheck != null && toCheck != typeof(object)) {
        var cur = toCheck.IsGenericType ? toCheck.GetGenericTypeDefinition() : toCheck;
        if (generic == cur) {
            return true;
        }
        toCheck = toCheck.BaseType;
    }
    return false;
}
if (IsSubclassOfRawGeneric(typeof(SearchBoxGeneric<>), c.GetType()))
{
    var prop = c.GetType().GetProperty("Value");
    object value = prop.GetValue(c);
    Console.WriteLine(value);
}
if (IsSubclassOfRawGeneric(typeof(SearchBoxGeneric<>), c.GetType()))
{
    dynamic dynObj = c;
    object value = dynObj.Value;
    Console.WriteLine(value);
}