通过显式转换为ref参数(C#) [英] Passing an explicit cast as a ref parameter (C#)

查看:130
本文介绍了通过显式转换为ref参数(C#)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类,它主要是一个大的阵列和一些相关的内政的包装。我有一个函数,它接受ref参数。当我通过类的实例到函数,我要在数组中被发送。

I have a class that is mostly a wrapper for a big array and some associated housekeeping. I have a function that takes a ref parameter. When I pass an instance of the class into the function, I want the array to get sent.

我认为显式转换。 。比方说,我有一个具有一个byte [] ref参数一些功能

I considered explicit casts. Let's say I have some function that has a byte[] ref parameter.

    public void SomeFunction(ref byte[] someBytes);

和我有一些类重载的显式转换。

And that I have some class with an overloaded explicit cast.

    class SomeClass
    {
        byte[] someBytes;
        public static explicit operator byte[](SomeClass someInstance)
        {
            return someInstance.someBytes;
        }
    }

现在我要打电话与类的功能参数

Now I want to call the function with the class as a parameter

    SomeClass someInstance = new SomeClass();
    SomeFunction(ref (byte[]) someInstance);



编译器会抱怨ref或out参数必须是可分配变量。我不知道如果我只是未能适当地按摩编译器,或者如果你真的只是不能做到这一点。

The compiler complains "a ref or out argument must be an assignable variable". I'm not sure if I'm just failing to massage the compiler properly or if you really just can't do that.

我认为是一个属性或函数返回值,但你不能传递那些由REF(并教育自己后,我明白为什么...)

I considered a Property or function return value, but you can't pass those by ref (and after educating myself I see why...)

我不希望使数组公共领域,但也不满足编译器。
我想我可以创建一个局部变量来引用与阵列,但是这是一个额外的代码行前,每个函数调用...

I'd prefer not to make the array a public field, but that does satisfy the compiler. I suppose I could just create a local variable to reference the array with, but that's an extra line of code before and after each function call...

编辑:它可能是值得注意的是,SomeFunction写由第三方而且我没有访问去改变它。更糟的是,我不认为自己参数实际上必须参考...

it might be worth noting that SomeFunction was written by a third party and I don't have access to change it. Worse, I don't think their parameter actually needs to be ref...

推荐答案

一个转换是不是分配的变量; 。你传递从显式类型转换操作符返回值

A cast is not an assignable variable; you're passing a return value from your explicit cast operator.

您可以把它当作一个参考之前创建一个变量持有正确的投值:

You can create a variable holding the properly cast value before passing it as a ref:

SomeClass someInstance = new SomeClass();
byte[] someBytes = (byte[])someInstance;
SomeFunction(ref someBytes);

请注意,现在是 someBytes 变量可被重新分配。你将不得不采取行动,重新分配 someInstance.someBytes 在调用 SomeFunction 之后一些方法,如果你想在内部 someInstance 的价值重新分配。

Note that it is now the someBytes variable which may be reassigned. You will have to take action to reassign someInstance.someBytes in some way after the call to SomeFunction if you want the internal value of someInstance to be reassigned.

这篇关于通过显式转换为ref参数(C#)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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