Skip to main content
 首页 » 编程设计

c#之在 C# 中使用 void 指针作为模板和函数参数

2024年02月24日19tintown

作为一个 C++ 狂热者,我迫切需要在 C# 中使用 void 指针。手头的任务要求我在编译时不知道某个变量的类型。 因此,我考虑准备一个结构,其中包含在运行时识别类型所需的所有信息。现在,这个想法在 C++ 中可行,但是,C# 并不完全像 C++。:wq 特别是,我需要定义一个:

    private List<KeyValuePair<string, KeyValuePair<string, void*>>> mappings; 

第一个问题从这里开始。 .Net 不允许我定义 eh KeyValuePair作为<string, void*> .我得到的错误是:错误 3 The type 'void*' may not be used as a type argument。 错误消息非常简单,但是,如果能够这样做,我将节省几天的工作时间。 第二个问题是在同一个街区。我需要定义这个函数:

 public unsafe void addMapping(string name, string internal_name, void* storage) 

同样,不允许,在这种情况下:错误 2 The type 'void*' may not be used as a type argument 有解决这些问题的方法吗?

感谢您的帮助!

请您参考如下方法:

在 C++ 中,void*可以指向任何东西。

在 C# 中,每个 thing class, structure, enumeration, and delegate源自 System::Object , 所以 object可以指任何实例。只需使用 KeyValuePair<string, object> .