我想知道你是否可以在下面有类似的东西:
namespace myNamespace
{
public string myString;
}
我找不到任何可以解释这一点的东西,可能是因为我搜索的关键字太糟糕了。谁能告诉我是否有办法做到这一点?
如果这是可能的,我可能搞砸了一些事情。无论哪种方式,我都想知道。
我想知道如何做到这一点,因为我想在整个命名空间中访问它,而不必在不同的类中访问 something.myString。这在我看来似乎合乎逻辑,但显然不可能。
您不能直接在以下字段中声明字段namespace
:
// doesn't compile
namespace myNamespace
{
public string myString; // <- syntax error
}
但是您可以在(C# 6.0+)的帮助下模拟这样的语法using static
:
namespace MyLibrary
{
// put myString within a static class
public static class MyStorage
{
// let turn field into property
public static string myString {get; set;}
}
}
然后使用静态类using static
:
// please, notice "using static"
using static MyLibrary.MyStorage;
namespace myNamespace
{
public class MyClass
{
public void MyMethod()
{
myString = "abc"; // as if it has been declared in the namespace
string test = myString;
...
}
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句