在静态类 C# ASP.NET Web 窗体中调用静态方法
我已将静态类 TestClass 放置在 App_Code 文件夹中。该类包含一个静态方法 TestMethod。从 Default.aspx.cs 通过 Button_Click 方法,我尝试调用 TestMethod。 - 测试 = TestClass.TestMethod()。 这会出现错误:“TestClass”由于其保护级别而无法访问。
感觉静态类和 _Default 类应该放置在公共命名空间中,但这会“排除”Default.aspx 控件引用。
我做错了什么?
I've placed a static class TestClass in the App_Code folder. The class contains a static method TestMethod. From Default.aspx.cs via Button_Click method, I'm trying to invoke TestMethod. - test = TestClass.TestMethod().
This gives error: 'TestClass' is inaccessible due to its protection level.
It feels like the static class and the _Default class should be placed into a common namespace, but this would "exclude" the Default.aspx controls references.
What am I doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您需要将
TestClass
声明为 public:类型的默认可见性为
internal
,对于类型定义的成员,默认可见性为private
。App_Code
文件夹被编译成自己的程序集,与编译后面的代码时创建的程序集不同。internal
类型不能在程序集之间共享(这不是 100% 正确,但在本例中是正确的),因此您会遇到此问题。You need to declare
TestClass
as public:The default visibility is
internal
for types andprivate
for members of a type definition. TheApp_Code
folder gets compiled into its own assembly, different from the assembly that is created when compiling the code behinds.internal
types cannot be shared between assemblies (that's not 100% true but true in this case), hence why you are having this problem.尝试将其设为公共静态。
Try to make it public static.
确保 TestClass 是公共的:
将类添加到 Visual Studio 时默认省略“public”。
Make sure TestClass is public:
The default when adding a class to Visual Studio is to omit the "public".
确保你的方法原型至少有“内部”范围。
Make sure you have at least 'internal' scope on your method prototype.
仅仅因为您的类是静态的并不意味着所有代码/程序集都可以访问它。确保您的静态类具有可通过 Web 表单访问的访问修饰符(即 public)。
Just because your class is static doesn't mean that it is accessible to all code/assemblies. Make sure that your static class has an access modifier (i.e. public) that is accessible by your web form.