【问题标题】:class accessibility & inheritance in ASP.Net C# 4.0ASP.Net C# 4.0 中的类可访问性和继承
【发布时间】:2012-10-31 23:18:34
【问题描述】:
namespace MyStyle
{
    public class Styles
    {                  
            //intended to store style.properties & style.values class 

        public sealed class sealdPropsClass 
        {
            public sealed const string DarkBlueColor = "darkBlue";
        }

        public static class staticPropsClass
        {
            public static const string LightBlueColor = "lightBlue";
        }
    }
}

这样访问:

 using MyStyles;
 
 string ColorBlue = Styles.sealedPropsClass.DarkBlueColor;

关于类和继承的另一个问题 我被警告不要使用static 修饰符

原因是:当前用户无法访问其他人 已经在访问该课程

通过当前页面或其他使用该类的 Web 应用程序。

我想从这个例子中理解什么:

1.

我如何在outer class 中包含样式(我应该这样做吗?):

所以我可以使用主题类的instance = 克隆,如下面的代码所示:

public Styles CurrentAppStyles = new Styles();

string darkColor = CurrentAppStyles.sealdPropsClass.DarkBlueColor

2.

如果我通过 MyStyle 命名空间导入

 using MyStyle; ///<-- is that an instance ? 

意味着它不会(如果在这种情况下出现 Exeption 错误)警告用户:

"Styles.SealedPropsClass.DarkBlueColor 正在使用中,请稍后再试..."

或者它实际上是在实例化整个 namespace(我认为在这种情况下会发生这种情况)

感谢您的经验和知识为我提供的巨大帮助!

更新(问题来源)

this is where i have been warned ,你能不能多解释一下???

这没有回答您的问题,但我注意到尚未指出这一点:您的邮件类很危险,因为它被声明为静态并且公开了公共静态字段。 **

** 更新 2** 我的错是我没有从 Joshuas 的评论中得到实际上是 在全球范围内共享状态是问题而不是访问问题......所以,我想在使用常量字段(字符串等......)的情况下不会有问题

【问题讨论】:

  • 你真的遇到这种错误吗?多个用户访问静态变量应该没有问题。
  • 你只是想让一个类来保存常量吗?如果是这样,那么你在考虑这个问题。只需将 Styles 设为一个填充了静态只读字符串的静态类,然后像这样访问它们; MyStyle.Styles.DarkBlue 等
  • 关于静态的警告是特定于在您的“邮件”示例中使用它的。就像 Joshua 所说的,将其设为静态意味着您在全球范围内共享状态。但是,如果您只是将它用于一些无状态的目的(例如存储常量),那也没关系。

标签: c# asp.net class inner-classes access-modifiers


【解决方案1】:

所以我现在可以理解的是,在所有情况下都不能避免使用静态类 例如 。扩展方法通过静态类使用,我的大多数子类都是静态的,例如:"

public class container // instanciated so name is not so relevant 
{                      // e.g : container c = new container()
                       // usage- c.utils.......
    public static class utils // used from an instance of container
    {
      public static int Str2int(string strToConvert)
      {
          return Convert.ToInt32(StrToConvert);
      }
    }
}

【讨论】:

    猜你喜欢
    • 2017-09-01
    • 1970-01-01
    • 2020-02-11
    • 1970-01-01
    • 1970-01-01
    • 2012-01-05
    • 2011-11-11
    • 1970-01-01
    • 2021-11-12
    相关资源
    最近更新 更多