我正在进入c#,我有这个问题:
namespace MyDataLayer
{
namespace Section1
{
public class MyClass
{
public class MyItem
{
public static string Property1{ get; set; }
}
public static MyItem GetItem()
{
MyItem theItem = new MyItem();
theItem.Property1 = "MyValue";
return theItem;
}
}
}
}
我在UserControl上有这样的代码:
using MyDataLayer.Section1;
public class MyClass
{
protected void MyMethod
{
MyClass.MyItem oItem = new MyClass.MyItem();
oItem = MyClass.GetItem();
someLiteral.Text = oItem.Property1;
}
}
一切正常,除了访问Property1。智能感知只给我“等于,GetHashCode, GetType,和ToString”作为选项。当我把鼠标移到oItem上时。Property1, Visual Studio给我这样的解释:
MemberMyDataLayer.Section1.MyClass.MyItem.Property1。get不能通过实例引用访问,而是用类型名限定它
我不确定这是什么意思,我用谷歌搜索了一下,但没能弄明白。
我也遇到过同样的问题——尽管几年后,有些人可能会发现一些有用的建议:
不要无缘无故地使用“静态”!
理解“静态”在运行时和编译时语义(行为)和语法方面的含义。
A static entity will be automatically constructed some time before
its first use.
A static entity has one storage location allocated, and that is
shared by all who access that entity.
A static entity can only be accessed through its type name, not
through an instance of that type.
A static method does not have an implicit ‘this’ argument, as does an
instance method. (And therefore a static method has less execution
overhead – one reason to use them.)
Think about thread safety when using static entities.
MSDN中关于静态的一些细节:
c#中的静态类
c#中的静态构造函数
我也遇到过同样的问题——尽管几年后,有些人可能会发现一些有用的建议:
不要无缘无故地使用“静态”!
理解“静态”在运行时和编译时语义(行为)和语法方面的含义。
A static entity will be automatically constructed some time before
its first use.
A static entity has one storage location allocated, and that is
shared by all who access that entity.
A static entity can only be accessed through its type name, not
through an instance of that type.
A static method does not have an implicit ‘this’ argument, as does an
instance method. (And therefore a static method has less execution
overhead – one reason to use them.)
Think about thread safety when using static entities.
MSDN中关于静态的一些细节:
c#中的静态类
c#中的静态构造函数