C#中的对象指针(object *) [英] Object pointers(object*) in C#

查看:793
本文介绍了C#中的对象指针(object *)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做的是,我想将一个指针传递给可能是任何类型的变量的函数(int,long,string,甚至是一个类,我的意思是我应该能够传递任何变量的指针).我就是这样

What I want to do is, I want to pass a pointer to a function that may be any type of a variable(int, long, string, even a class I mean I should be able to pass any variable's pointer). I'm doing this like that

unsafe class whatever
{
    whatever(object* variable)
    {
          this.variable = variable;
    }
}

错误信息:无法获取其地址,获取其大小或声明一个指向托管类型(对象")的指针

ERROR IS: Cannot take the address of, get the size of, or declare a pointer to a managed type ('object')

为什么我要做的是,我将存储通过构造函数传递的变量,并使用其ToString()方法,试图创建一个适用于控制台应用程序的类,并使用其更新后的变量刷新变量.

Why I want to do is, I will store the variables passed through the constructor and will use their ToString() method, I'm trying to make a class that is for console applications, Refreshing the variables with their updated variables.

如果我可以那样做,我的代码将像这样

If I could do it like that My code will look like that

unsafe class whatever
{
    whatever(object* variable)
    {
        this.variable = variable;
    }

    object* variable;

    public override string ToString()
    {
        return *variable.ToString();
    }
}

推荐答案

也许您应该传递一个委托,您的类可以使用该委托来获取对象字符串".

Maybe you should pass in a delegate that your class can use to obtain the "object string".

class MyFancyClass
{
    Func<string> getObjectString;

    public MyFancyClass(Func<string> getObjectString)
    {
        this.getObjectString = getObjectString;
    }

    private MyOtherThread()
    {
        // ...
        string desc = getObjectString();
        // ...
    }
}

// ...
long value = 34;
MyFancyClass fancy = new MyFancyClass(() => value.ToString());

// ...
value = 88;
// getObjectString() should now reflect the new value.
// The variable is captured in the lambdas closure.

但是请小心,因为委托是从另一个线程调用的,并且仅调用ToString()可能并非对所有对象都是安全的,并且需要锁定.但是,委托可以允许调用者执行此操作,具体取决于对象.

Be careful though, because the delegate is called from another thread and simply calling ToString() may not be safe for all objects and require locking. However a delegate allows the caller to do this, depending on the object.

指针将变得丑陋,需要不安全的代码并且不稳定.如果您没有明确地使指针固定,则垃圾收集器可以自由地移动对象.引用无法存储,您只能传递它们.

Pointers will get ugly, require unsafe code and aren't stable. The garbage collector can move objects around freely, if you don't explicitly make the pointers fixed. References can't be stored and you can only pass them around.

这篇关于C#中的对象指针(object *)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆