首页 > 解决方案 > 强制转换 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#casting

解决方案


推荐阅读