C# var 的用法,获取指定位置的value和type,重写C#

C# var 的用法,获取指定位置的value和type,重写C#

问题描述:

原代码是这样写的,

var current = ProjectTree.SelectedItem.Tag;

其中 current代表

img

ProjectTree代表

img

SelectedItem代表

img

Tag代表

img

我理解的是ProjectTree.SelectedItem.Tag是在GUI界面中指定位置所表示的类。

我debug了下,我选中了某个指定位置,

img

这个是current的值

img

可以看到, current的value是{Siemens.Engineering.SW.Blocks.PlcBlockSystemGroup}, type是 object{Siemens.Engineering.SW.Blocks.PlcBlockSystemGroup}

{Siemens.Engineering.SW.Blocks.PlcBlockSystemGroup}这个的定义如下

img

目前我想要实现的是重新写current 这个var,不通过选择GUI界面中指定位置,而是通过代码实现。
我试了这个代码,但是报错,
PlcSystemBlockGroup current = new PlcSystemBlockGroup();

img

如何才能通过写代码的形式获得这个对应的current呢?

主要想用这一个函数, 先写调用指令

OpennessHelper.ImportItem(current as IEngineeringObject, file, ImportOptions.Override);


ImportItem函数如下:

public static void ImportItem(IEngineeringCompositionOrObject destination, string filePath, ImportOptions importOption)
        {
            if (destination == null)
                throw new ArgumentNullException(nameof(destination), "Parameter is null");
            if (string.IsNullOrEmpty(filePath))
                throw new ArgumentException("Parameter is null or empty", nameof(filePath));

            var fileInfo = new FileInfo(filePath);
            filePath = fileInfo.FullName;
            if (destination is CycleComposition || destination is ConnectionComposition || destination is MultiLingualGraphicComposition
                || destination is GraphicListComposition || destination is TextListComposition)
            {
                var parameter = new Dictionary<Type, object>();
                parameter.Add(typeof(string), filePath);
                parameter.Add(typeof(ImportOptions), importOption);
                // Export prüfen
                (destination as IEngineeringComposition).Invoke("Import", parameter);
            }
            //folder2

            //  (destination as PlcSoftware).TagTables.Import(fileInfo, importOption);

            else if (destination is PlcBlockGroup)
            {
                if (Path.GetExtension(filePath).Equals(".xml"))
                    (destination as PlcBlockGroup).Blocks.Import(fileInfo, importOption);
                else
                {
                    var currentDestination = destination as IEngineeringObject;
                    while (!(currentDestination is PlcSoftware))
                    {
                        currentDestination = currentDestination.Parent;
                    }
                    var col = (currentDestination as PlcSoftware).ExternalSourceGroup.ExternalSources;

                    var sourceName = Path.GetRandomFileName();
                    sourceName = Path.ChangeExtension(sourceName, ".src");
                    var src = col.CreateFromFile(sourceName, filePath);
                    src.GenerateBlocksFromSource();
                    src.Delete();
                }
            }


好这个需要结合你的总体需求考虑,new一个对象数据从哪里来?实现什么功能?没交待清楚。

你要干啥

这个可以看出是如何构建对象的吗?

img