gpt4 book ai didi

C# 将类作为字符串传递并将其从数组中转换

转载 作者:太空宇宙 更新时间:2023-11-03 11:05:16 25 4
gpt4 key购买 nike

我有几个嵌套类,如“BlueprintsManager.WorkingStandardBlueprint”和具有它们实例的 ArrayList。我想将它们作为参数传递给方法,例如:

private void ShowBlueprints(string class_str, ArrayList class_array)
{
// class_str would be passed as "BlueprintsManager.WorkingStandardBlueprint"
// how here I can access class_str as a class and cast class_array to it, to access some variables.
// for example, I need to access some BlueprintsManager.WorkingStandardBlueprint public variables.
}

我一直在摆弄反射、泛型,但我仍然无法让它工作。

谢谢。

最佳答案

你应该为此使用泛型:

private void ShowBlueprints<T>(List<T> class_array)
{
for (BlueprintsManager.WorkingStandardBlueprint item in class_array)
{
if(typeof T is BlueprintsManager.WorkingStandardBlueprint)
{
Console.WriteLine(((BlueprintsManager.WorkingStandardBlueprint)item).whateverpropertyyouhavedefined);
}
}
}

现在你可以这样调用方法了:

ShowBluePrints<BlueprintsManager.WorkingStandardBlueprint>(myblueprints);

编辑 在评论中,OP 表示所有属性都是相同的。此解决方案可行:

class BaseClass
{
string Name {get; set;}
int id {get; set;}
}

class BlueprintsManager
{
class WorkingStandardBlueprint : BaseClass
{

}
}

private void ShowBlueprints<T>(List<T> class_array) where T : BaseClass
{
for (T item in class_array)
{
Console.WriteLine(item.Name);
}
}

关于C# 将类作为字符串传递并将其从数组中转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16126430/

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