gpt4 book ai didi

c# - 从类型集合中获取公共(public)基类的最简单方法

转载 作者:太空狗 更新时间:2023-10-30 00:47:34 26 4
gpt4 key购买 nike

我正在构建一个显示集合中项目属性的自定义属性网格。我想要做的是只显示网格中每个项目共有的属性。我假设最好的方法是在集合中找到每种类型的公共(public)基类并显示它的属性。有没有更简单的方法?你能给我一个代码示例来说明执行此操作的最佳方法吗?

最佳答案

您可以使用持续检查公共(public)基类的方法来做到这一点。我使用 Type 类的 BaseClass 功能快速编写了这个。您不必使用数组、列表或其他 IEnumerable 只需对此进行少量修改即可使用。

我测试了它:

static void Main(string[] args)
{
Console.WriteLine("Common Types: " + GetCommonBaseClass(new Type[] {typeof(OleDbCommand), typeof(OdbcCommand), typeof(SqlCommand)}).ToString());
}

并得到了 DbCommand 的正确答案。这是我的代码。

    static Type GetCommonBaseClass(Type[] types)
{
if (types.Length == 0)
return (typeof(object));
else if (types.Length == 1)
return (types[0]);

// Copy the parameter so we can substitute base class types in the array without messing up the caller
Type[] temp = new Type[types.Length];

for (int i = 0; i < types.Length; i++)
{
temp[i] = types[i];
}

bool checkPass = false;

Type tested = null;

while (!checkPass)
{
tested = temp[0];

checkPass = true;

for (int i = 1; i < temp.Length; i++)
{
if (tested.Equals(temp[i]))
continue;
else
{
// If the tested common basetype (current) is the indexed type's base type
// then we can continue with the test by making the indexed type to be its base type
if (tested.Equals(temp[i].BaseType))
{
temp[i] = temp[i].BaseType;
continue;
}
// If the tested type is the indexed type's base type, then we need to change all indexed types
// before the current type (which are all identical) to be that base type and restart this loop
else if (tested.BaseType.Equals(temp[i]))
{
for (int j = 0; j <= i - 1; j++)
{
temp[j] = temp[j].BaseType;
}

checkPass = false;
break;
}
// The indexed type and the tested type are not related
// So make everything from index 0 up to and including the current indexed type to be their base type
// because the common base type must be further back
else
{
for (int j = 0; j <= i; j++)
{
temp[j] = temp[j].BaseType;
}

checkPass = false;
break;
}
}
}

// If execution has reached here and checkPass is true, we have found our common base type,
// if checkPass is false, the process starts over with the modified types
}

// There's always at least object
return tested;
}

关于c# - 从类型集合中获取公共(public)基类的最简单方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/353430/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com