如何将“using”类型对象传递给函数?
我有一个如下所示的代码:
using (DC dc = new DC())
{
f(dc.obj, a);
}
void f(DC dc, int a)
{
...
dc.obj = a;
}
它不起作用 - 抱怨对象引用和非静态字段。这是一个控制台应用程序,因此它具有 Main() 函数。我应该如何让它发挥作用?我尝试按照要求添加引用:
我有一个看起来像这样的代码:
using (DC dc = new DC())
{
f(ref dc.obj, a);
}
void f(ref DC dc, int a)
{
...
dc.obj = a;
}
但它仍然不起作用
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这与 using 语句无关。您正尝试从 Main 调用非静态成员函数,该函数是静态的。您不能这样做,因为“f”是一个实例方法,即您必须在 Program 类的实例上或从 Program 类的实例调用它。因此,您需要使函数 f 静态。
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 是一个实例方法,大概在 Program 类中,对吗?如果从 Main 调用 f,则不存在 Program 实例,因为 Main 是静态方法。将 f 更改为静态:
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: