我是否误解了 C# 中的变量访问?
Am I misunderstanding variable access in C#?
我有一个 Utils.dll
的来源看起来像这样:
using System;
namespace Utils
{
public static class A
{
public static string B()
{
string foo = "Lorem ipsum dolor sit amet...";
return "abc";
}
}
}
和一个源代码看起来像这样的可执行文件:
using System;
using Utils;
public class Program
{
public static void Main(string[] args)
{
Console.WriteLine(A.B());
Console.WriteLine(A.B.foo);
}
}
我希望能够从使用 Utils.dll
编译的任何 C# 可执行文件访问 foo
,但显然不能;编译器(我正在使用 Mono)说 error CS0119: Expression denotes a 'method group', where a 'variable', 'value' or 'type' was expected
。我试过将 public
、static
和 const
以各种排列方式添加到 string foo
之前,但没有成功。
我是不是误解了 C# 中变量访问的工作原理?有什么方法可以完成我想做的事情吗?
是的,你误会了。
你的 foo 字符串声明为局部变量,所以只有方法 B 可以访问它。顺便说一句,我也不知道你的 B 对象是一个方法(在那种情况下它应该是 B() 而不是 B)还是一个 属性 (但 B 没有得到或设置所以..)。
为什么你需要从 B 访问 foo,如果 B returns "abc" 而不是 foo ?
我有一个 Utils.dll
的来源看起来像这样:
using System;
namespace Utils
{
public static class A
{
public static string B()
{
string foo = "Lorem ipsum dolor sit amet...";
return "abc";
}
}
}
和一个源代码看起来像这样的可执行文件:
using System;
using Utils;
public class Program
{
public static void Main(string[] args)
{
Console.WriteLine(A.B());
Console.WriteLine(A.B.foo);
}
}
我希望能够从使用 Utils.dll
编译的任何 C# 可执行文件访问 foo
,但显然不能;编译器(我正在使用 Mono)说 error CS0119: Expression denotes a 'method group', where a 'variable', 'value' or 'type' was expected
。我试过将 public
、static
和 const
以各种排列方式添加到 string foo
之前,但没有成功。
我是不是误解了 C# 中变量访问的工作原理?有什么方法可以完成我想做的事情吗?
是的,你误会了。
你的 foo 字符串声明为局部变量,所以只有方法 B 可以访问它。顺便说一句,我也不知道你的 B 对象是一个方法(在那种情况下它应该是 B() 而不是 B)还是一个 属性 (但 B 没有得到或设置所以..)。
为什么你需要从 B 访问 foo,如果 B returns "abc" 而不是 foo ?