C# 从类文件调用函数而不创建该类的对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8938446/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 05:18:49  来源:igfitidea点击:

Call a function From Class file without creating Object of that class

c#asp.net

提问by Moiz Kachwala

I have created a function in a class. and i want to call it throughout my project. but i don't want to create the object of that class in every page. is there any global declaration for that class so that we can call in every page ? Inheritance is not possible in code behind file of aspx page .cs file.

我在类中创建了一个函数。我想在我的整个项目中调用它。但我不想在每个页面中创建该类的对象。该类是否有任何全局声明,以便我们可以在每个页面中调用?在 aspx 页面 .cs 文件的代码隐藏文件中无法继承。

采纳答案by Pranay Rana

You need to create a StaticMethod in your class so that you can call the function without creating an object of that class as shown in following snippet:

您需要Static在您的类中创建一个方法,以便您可以在不创建该类的对象的情况下调用该函数,如下面的代码片段所示:

public class myclass
{
 public static returntype methodname()
 {
    //your code
 }
}

to call the function just use

调用函数只需使用

//ClassName.MethodName();
myclass.methodname();

you can have look at MSDN: Static Members

你可以看看 MSDN:静态成员

Suggestion

建议

One more resolution to your problem is to make use of SINGLETON DESIGN PATTERN

解决您的问题的一种方法是使用SINGLETON DESIGN PATTERN

Intent

意图

  1. Ensure that only one instance of a class is created.
  2. Provide a global point of access to the object.
  1. 确保只创建一个类的一个实例。
  2. 提供对对象的全局访问点。

UML diagram

UML图

回答by Jon Skeet

You just need to make it a static method:

你只需要让它成为一个静态方法:

public class Foo
{
    public static void Bar()
    {
        ...
    }
}

Then from anywhere:

然后从任何地方:

Foo.Bar();

Note that because you're not calling the method on an instance of the type, there won't be any instance-specific state - you'll have access to any staticvariables, but not any instancevariables.

请注意,因为您不是在该类型的实例上调用该方法,所以不会有任何特定于实例的状态 - 您将可以访问任何静态变量,但不能访问任何实例变量。

If you needinstance-specific state, you'll need to have an instance - and the best way of getting hold of an appropriate instance will really depend on what you're trying to achieve. If you could give us more information about the class and the method, we may be able to help you more.

如果您需要特定于实例的状态,则需要有一个实例 - 获取适当实例的最佳方法实际上取决于您要实现的目标。如果您可以向我们提供有关类和方法的更多信息,我们可能会为您提供更多帮助。

Admittedly from what I remember, dependency injection in ASP.NET (pre-MVC) is a bit of a pain, but you may well want to look into that - if the method mutates any static state, you'll end up with something which is hard to test and hard to reason about in terms of threading.

诚然,根据我的记忆,ASP.NET(MVC 之前)中的依赖注入有点痛苦,但您可能想研究一下 - 如果该方法改变任何静态状态,您最终会得到一些在线程方面很难测试和推理。