gpt4 book ai didi

c# - 测量类型之间的关系继承距离

转载 作者:行者123 更新时间:2023-11-30 16:55:14 24 4
gpt4 key购买 nike

有谁知道我如何(或者如果有现有算法)测量两个 .NET 类型之间的关系距离?

我指的是从对象 A 到对象 B 所需的分层树中的“步骤”数。

例如,如果对象 A 是一个 Button,而对象 B 是一个 LinkBut​​ton,则将有 2 个步骤,Button -> WebControl -> LinkBut​​ton。我是否需要创建自己的静态继承树并使用路径查找算法,或者是否有一种方法可以动态查看 .NET 的继承结构以计算两个对象之间的距离?

最佳答案

非通用方式(也不必明确指定父/子):

private static int CalulateDistanceOneWay(Type firstType, Type secondType)
{
var chain = new List<Type>();
while (firstType != typeof(object))
{
chain.Add(firstType);
firstType = firstType.BaseType;
}

return chain.IndexOf(secondType);
}

// returns -1 for invalid input, distance between types otherwise
public static int CalculateDistance(Type firstType, Type secondType)
{
int result = CalulateDistanceOneWay(firstType, secondType);
if (result >= 0)
{
return result;
}

return CalulateDistanceOneWay(secondType, firstType);
}

编辑:更新以计算表亲:

public class DistanceResult
{
public Type SharedAncestor { get; private set; }
public int FirstTypeDistance { get; private set; }
public int SecondTypeDistance { get; private set; }

public DistanceResult(Type sharedAncestor, int firstTypeDistance, int secondTypeDistance)
{
SharedAncestor = sharedAncestor;
FirstTypeDistance = firstTypeDistance;
SecondTypeDistance = secondTypeDistance;
}
}

static DistanceResult CalculateDistance(Type firstType, Type secondType)
{
var firstChain = new List<Type>();
while (firstType != typeof(object))
{
firstChain.Add(firstType);
firstType = firstType.BaseType;
}
firstChain.Add(typeof(object));

var secondChain = new List<Type>();
while(secondType != typeof(object))
{
secondChain.Add(secondType);
secondType = secondType.BaseType;
}
secondChain.Add(typeof(object));

for(var i = 0; i < secondChain.Count; i++)
{
var type = secondChain[i];
int index = firstChain.IndexOf(type);
if (index >= 0)
{
return new DistanceResult(firstChain[index], index, i);
}
}

return null;
}

关于c# - 测量类型之间的关系继承距离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29746090/

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