简体   繁体   English

C#-在常规类中公开静态类?

[英]C# - Expose a Static Class inside a normal class?

Here is an easy example: 这是一个简单的例子:

ASP.NET provides several static classes based around the membership provider. ASP.NET提供了一些基于成员资格提供程序的静态类。 We are forever using them in our pages. 我们永远在页面中使用它们。 We also have a need to extend the base System.Web.UI.Page class. 我们还需要扩展基础System.Web.UI.Page类。 So, one thought we had was to expose the various static classes in our OurCompany.Web.UI.Page implementation. 因此,我们曾经想到的是在OurCompany.Web.UI.Page实现中公开各种静态类。

We cannot use a variable: 我们不能使用变量:

System.Web.Security.Roles myRoles;

We cannot expose it as a property: 我们不能将其公开为属性:

internal System.Web.Security.Roles Roles { get { return System.Web.Security.Roles; } }

We cannot inherit it: 我们不能继承它:

internal class Roles : System.Web.Security.Roles

Is it possible to expose the static class? 是否可以公开静态类?

What do you mean by "expose"? 你所说的“暴露”是什么意思? The static classes are already available to whoever wants to use them. 静态类已可供任何想要使用它们的人使用。

It sounds like you're possibly trying to derive from a class or use a property just to avoid typing as much - that's a bad idea. 听起来您可能正试图从一个类派生或使用一个属性只是为了避免过多键入-这是一个坏主意。 Inheritance is for specialization, not to make names easier to reach :) Just have a using directive: 继承是为了专业化,而不是为了使名称更容易达到:)仅具有using指令:

using System.Web.Security;

and then you can use Roles.XXX wherever you want in that code. 然后您可以在该代码中的任何位置使用Roles.XXX

我不一定知道为什么要这样做,但是您可以做的一件事是创建自定义Roles类,并从Static类中克隆方法,然后在这些方法中仅调用static类中的方法。

Are you trying to extend System.Web.UI.Page with your own extra methods/etc.? 您是否正在尝试使用自己的其他方法/ etc扩展System.Web.UI.Page? If so, why not use inheritance and make your Page inherit from System.Web.UI.Page. 如果是这样,为什么不使用继承并使您的Page从System.Web.UI.Page继承。 Then all you have to do is change your various ASPX pages to use your Page instead of the default. 然后,您要做的就是更改各种ASPX页面以使用您的Page而不是默认页面。 If this is what you want, check out this article for a decent example. 如果这是您想要的, 请查看本文中的示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM