简体   繁体   English

通过'ref'传递 - c#

[英]Passing by 'ref' - c#

Much to my dismay, the follow code wont compile. 令我沮丧的是,以下代码不会编译。

It will however compile if I remove the ref keyword. 但是,如果我删除ref关键字,它将编译。

class xyz
{
    static void foo(ref object aaa)
    {
    }

    static void bar()
    {
        string bbb="";
        foo(ref bbb);
        //foo(ref (object)bbb); also doesnt work
    }
}
  1. Can anyone explain this? 有谁能解释一下? Im guessing it has something to do with ref's being very strict with derived classes. 我猜这与ref对派生类非常严格有关。

  2. Is there any way I can pass an object of type string to foo(ref object varname) ? 有什么办法可以将string类型的对象传递给foo(ref object varname)吗?

It has to be an exact match, else foo could do: 它必须完全匹配,否则foo可以做到:

aaa = 123;

which would be valid for foo (it will box the int to an object ), but not for bar (where it is a string ). 哪个对foo有效(它会将int到一个object ),但不适用于bar (它是一个string )。

Two immediate options; 两个直接选择; firstly, use an intermediate variable and a type-check: 首先,使用中间变量和类型检查:

object tmp = bbb;
foo(ref tmp);
bbb = (string)tmp;

or alternatively, maybe try generics ( foo<T>(ref T aaa) ); 或者,也许尝试泛型( foo<T>(ref T aaa) ); or treat bbb as object instead of string . 或者将bbb视为object而不是string

No, there isn't. 不,没有。 Imagine the following: 想象一下:

static void Foo(ref object obj)
{
    obj = new SomeObject();
}

static void Bar()
{
    string s = "";
    Foo(ref s);
}

Foo would try to assign a SomeObject to a variable that's actually a string ! Foo会尝试将SomeObject分配给一个实际上是string的变量!

When you pass a varaible by reference, it has to match the type exactly. 当您通过引用传递变量时,它必须与该类型完全匹配。

You can call the method by creating another varaible with the correct type: 您可以通过创建具有正确类型的另一个变量来调用该方法:

string bbb = "";
object o = bbb;
foo(ref o);

If you want the changed value back in the string variable, you have to check the type and cast it: 如果您希望将更改后的值返回到字符串变量中,则必须检查类型并将其强制转换:

bbb = o as string;

Consider using a return value instead of the ref keyword, and just return the changed value: 考虑使用返回值而不是ref关键字,只返回更改的值:

static object foo(object aaa) {

Usage: 用法:

o = foo(o);

You have to use the exact same type. 您必须使用完全相同的类型。 You can use advantage of dynamic 您可以利用dynamic优势

public static void foo(ref object a)
{
    a = "foo";
}

static void Main(string[] args)
{
    string bbb = "";
    dynamic a = bbb;        // or object
    foo(ref a);
    bbb = a;                // if it was object you need to cast to string

    Console.WriteLine(bbb); // foo
}

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

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