简体   繁体   English

结构C#中的托管指针

[英]Managed Pointer in a Structure C#

i'm trying to write a generic function which should be able to parse a xml file 我正在尝试编写一个应该能够解析xml文件的通用函数

here is the code 这是代码

    public struct XmlArg
    {
        public string Name;
        public Type T;
        public object Value;
    };

    static bool ParseXmlArgs(XmlReader xml, params XmlArg[] args)
    {
        for (int i = 0; i < args.Length; ++i)
        {
            if (xml.MoveToContent() != XmlNodeType.Element || xml.Name != args[i].Name)
            {
                return false;
            }
            args[i].Value = xml.ReadElementContentAs(args[i].T, null);
        }
        return true;
    }

    static void Main(string[] args)
    {
        int a = 0;

        ParseXmlArgs(
            XmlTextReader.Create("C:\\Users\\Yazilim\\Desktop\\XML.xml"),
            new XmlArg[]{
                new XmlArg() { Name = "ErrorCode", T = typeof(int), Value = a}});
    }

i know that i should pass a's pointer to Value ( it's type should be some different type other than object of course ) 我知道我应该将a的指针传递给Value(它的类型应该是不同于object的其他类型)

but i don't want it to be non-managed way. 但我不希望它成为非托管方式。

is there any managed way to use a variable's pointer in structure ? 有没有在结构中使用变量指针的托管方式?

( the function may be wrong or incorrect, and it's not the point ) (该功能可能是错误的或不正确的,这不是重点)

Assuming that you want XmlArg.Value to point to a instead of just clone its value, then the answer is just "You can't". 假设您希望XmlArg.Value 指向 a而不是仅克隆其值,那么答案就是“您不能”。 There is no address-of operator in C#, and that is for good reasons so, because you could create a reference to a variable on the stack (like your a is). C#中没有地址运算符,这是有充分理由的,因为您可以在堆栈上创建对变量的引用(就像您的a is一样)。 When you run out of scope, that variable contains garbage and then ZONK. 当超出范围时,该变量包含垃圾,然后包含ZONK。

Check this one out : Struct Pointer Initialization in C# . 请检查以下内容: C#中的结构指针初始化

Also, from the Microsoft docs regarding structs :Structs can also contain constructors, constants, fields, methods, properties, indexers, operators, events, and nested types, although if several such members are required, you should consider making your type a class instead. 同样,从Microsoft文档中获取有关struct的信息:结构还可以包含构造函数,常量,字段,方法,属性,索引器,运算符,事件和嵌套类型,尽管如果需要多个此类成员,则应考虑将您的类型设为类。

Hope that helps! 希望有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM