开发者

How to pass "using"-type objects to a function?

I have a code that looks like this:

开发者_如何学运维
using (DC dc = new DC())
{
    f(dc.obj, a);
}


void f(DC dc, int a)
{
    ...
    dc.obj = a;
}

It doesnt work - complains about object reference and non-static fields. This is a console application, so it has Main() function. How should I make it work? I tried adding references as it asked:

I have a code that looks like this:

using (DC dc = new DC())
{
    f(ref dc.obj, a);
}


void f(ref DC dc, int a)
{
    ...
    dc.obj = a;
}

but it still didnt work


This has nothing to do with the using statement. You are trying to call a non-static member function from Main, which is static. You cannot do that because 'f' is an instance method, i.e., you must call it on or from an instance of your Program class. So, you need to make your function f static.


f is an instance method, presumably in the Program class, right? If you are calling f from Main, then there is no instance of Program, because Main is a static method. Change f to be static:

static void f(DC dc, int a) { ... }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜