English 中文(简体)
取证——c
原标题:Passing by ref - c#
  • 时间:2011-06-16 12:20:34
  •  标签:
  • c#
  • ref

令我感到沮丧的是,随后的法典赢得了汇编。

It will however compile if I remove the ref keyword.

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.

  2. Is there any way I can pass an object of type string to foo(ref object varname)?

最佳回答

它必须是确切的匹配,否则是foo。 可以:

aaa = 123;

适用于<代码>foo (t)int to an object, but not for bar (如果是<条码>,则。)

两种直接选择:第一,使用中间变量和打字机:

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

或者,或许可以尝试通用(foo<T>ref T aaaa);或将bb作为object而不是string处理。

问题回答

无。 设想如下:

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

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

Foo将尝试将SomeObject分配给一个实际上为string的变量!

如果你通过提及即可释放,则必须准确匹配。

You can call the method by creating another varaible with the correct type:

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

如果你想要在扼制变量中重新调整价值,那么你必须检查其类型并投放:

bbb = o as string;

考虑使用收益价值而不是<代码>ref关键词,并仅退还已改变的价值:

static object foo(object aaa) {

使用:

o = foo(o);

你们必须使用同样的类型。 您可利用<代码>动力学

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
}




相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签