c# - 强制转换 C# 所需的参数是什么
问题描述
最小可重现示例基本抽象类:
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Linq;
namespace YangHandlerTool
{
public abstract class YangNode
{
public string Name { get; set; }
/// <summary>
/// This is here to force YangNode constructor with Name parameter.
/// </summary>
private YangNode() { }
public YangNode(string name) { Name = name; }
}
}
添加“类型”属性的子级
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Linq;
namespace YangHandlerTool
{
public class Leaf : YangNode
{
public string Type { get; set; }
public Leaf(string leafname) : base(leafname){ }
}
}
添加“类型”属性的其他子项
using System;
namespace YangHandlerTool
{
public class LeafList : YangNode
{
public string Type { get; set; }
public LeafList(string leafname) : base(leafname) { }
}
}
主要的
using System;
using System.Collections.Generic;
namespace YangHandlerTool
{
class Program
{
static void Main(string[] args)
{
List<YangNode> yangnodes = new List<YangNode>();
yangnodes.Add(new Leaf("leafname"));
for (int i = 0; i < yangnodes.Count; i++)
{
if (IsLeaf(i))
{
///I want to call SetTypeOfNode with the intention to cast to Leaf
SetTypeOfNode(yangnodes[i]);
}
if (IsLeafList(i))
{
///I want to call SetTypeOfNode with the intention to cast to LeafList
SetTypeOfNode(yangnodes[i]);
}
}
}
private static void SetTypeOfNode(YangNode inputnode)
{
///Desired
//Replace GIVENANYCLASSNAME with any given classname as parameter
//((GIVENANYCLASSNAME)inputnode).Type = "value";
((Leaf)inputnode).Type = "value";
}
/// <summary>
/// It is 100% guaranteed that the item is a Leaf.
/// </summary>
private static bool IsLeaf(int index)
{
return index == 0;
}
private static bool IsLeafList(int index)
{
return index == 1;
}
}
}
在函数“private static void SetTypeOfNode(YangNode inputnode)”中,我希望能够给一个类作为参数来转换。为了在我的实际铸造程序中节省 100 多行,例如:
((Leaf)inputnode).Type = "value";
((LeafList)inputnode).Type = "value";
((AnothertypeInheritedfromYangnode)inputnode).Type = "value";
((AnothertypeInheritedfromYangnode2)inputnode).Type = "value";
...
如何将 Classname 作为参数传递给转换参数?
解决方案
推荐阅读
- c# - 从 Docker 运行的自动扩展 Kafka Consumer
- javascript - 我如何描述这两种价值传递方式之间的区别?
- java - 仅使用 Springboot 和 MongoDB 比较 YYYY-MM 部分日期
- pine-script - Strategy.long 后第二次交叉,Pine 脚本
- c# - 在长时间运行的工作人员服务中创建 HttpClient 对象的建议方法是什么
- bots - 对不和谐机器人的编码感到困惑
- reactjs - 在不渲染父组件 React js 的情况下重新渲染子组件
- javascript - forEach - 在 Redux 中向 action.data 添加键/值 - console.log 有效,但 Redux 状态未更新
- ios - (iOS)无法使用 AVURLAsset 和 AVAsset 阅读器从 RAM 而不是文件读取视频帧
- excel - 使用填充功能