Programing

C #에서 정적 클래스를 사용하는 경우

lottogame 2020. 10. 3. 09:47
반응형

C #에서 정적 클래스를 사용하는 경우 [중복]


이 질문에 이미 답변이 있습니다.

다음 정적 클래스를 사용할 때 MSDN이 말하는 내용입니다 .

static class CompanyInfo
{
    public static string GetCompanyName() { return "CompanyName"; }
    public static string GetCompanyAddress() { return "CompanyAddress"; }
    //...
}

특정 개체와 연결되지 않은 메서드의 구성 단위로 정적 클래스를 사용합니다. 또한 정적 클래스는 메서드를 호출하기 위해 개체를 만들 필요가 없기 때문에 구현을 더 간단하고 빠르게 만들 수 있습니다. System 네임 스페이스에있는 Math 클래스의 메서드와 같이 의미있는 방식으로 클래스 내부의 메서드를 구성하는 것이 유용합니다.

나에게이 예제는 정적 클래스에 대해 가능한 많은 사용 시나리오를 다루지 않는 것 같습니다. 과거에는 관련 함수의 상태 비 저장 스위트에 정적 클래스를 사용했지만 그게 전부입니다. 그렇다면 어떤 상황에서 클래스를 정적으로 선언해야할까요?


이전 Stack Overflow 답변 : Class with single method-best approach 에서 정적 클래스에 대한 생각을 썼습니다 .

나는 정적 메서드로 채워진 유틸리티 클래스를 좋아했습니다. 그들은 중복성과 유지 관리 지옥을 유발할 수있는 도우미 메서드를 대대적으로 통합했습니다. 사용하기 매우 쉽고, 인스턴스화도, 폐기도 필요하지 않습니다. 나는 이것이 서비스 지향 아키텍처를 만들려는 나의 첫 번째 무의식적 시도라고 생각합니다. 그러나 시스템이 성장함에 따라 드래곤이 등장합니다.

다형성

즐겁게 윙윙 거리는 UtilityClass.SomeMethod 메소드가 있다고 가정 해 보겠습니다. 갑자기 기능을 약간 변경해야합니다. 대부분의 기능은 동일하지만 그럼에도 불구하고 몇 가지 부분을 변경해야합니다. 정적 메서드가 아니었다면 파생 클래스를 만들고 필요에 따라 메서드 내용을 변경할 수 있습니다. 정적 방법이므로 할 수 없습니다. 물론, 이전 메소드 이전이나 이후에 기능을 추가해야하는 경우 새 클래스를 만들고 그 안에 이전 클래스를 호출 할 수 있습니다.

인터페이스 문제

논리적 인 이유로 인터페이스를 통해 정적 메서드를 정의 할 수 없습니다. 정적 메서드를 재정의 할 수 없기 때문에 정적 클래스는 인터페이스로 전달해야 할 때 쓸모가 없습니다. 이로 인해 전략 패턴의 일부로 정적 클래스를 사용할 수 없습니다. 인터페이스 대신 델리게이트를 전달 하여 일부 문제를 패치 할 수 있습니다 .

테스팅

이것은 기본적으로 위에서 언급 한 인터페이스 문제와 함께 진행됩니다. 구현을 교환하는 능력이 매우 제한되어 있기 때문에 프로덕션 코드를 테스트 코드로 바꾸는데도 어려움을 겪을 것입니다. 다시 말하지만, 우리는 그것들을 래핑 할 수 있지만, 실제 개체 대신 래퍼를 받아 들일 수 있도록 코드의 많은 부분을 변경해야합니다.

블롭 육성

정적 메서드는 일반적으로 유틸리티 메서드로 사용되며 유틸리티 메서드는 일반적으로 다른 목적을 갖기 때문에 비 일관성 기능으로 가득 찬 큰 클래스로 빠르게 끝날 것입니다. 이상적으로는 각 클래스가 시스템 내에서 단일 목적을 가져야합니다. 목적이 잘 정의되어있는 한 5 배의 수업을 받고 싶습니다.

매개 변수 크리프

우선, 그 작고 귀엽고 순진한 정적 메서드는 단일 매개 변수를 사용할 수 있습니다. 기능이 성장함에 따라 몇 가지 새로운 매개 변수가 추가됩니다. 곧 선택적 매개 변수가 추가되어 메서드의 오버로드를 생성합니다 (또는이를 지원하는 언어로 기본값을 추가합니다). 머지 않아 우리는 10 개의 매개 변수를 취하는 메소드를 갖게되었습니다. 처음 세 개만 실제로 필요하며 매개 변수 4-7은 선택 사항입니다. 그러나 매개 변수 6이 지정되면 7-9도 채워야합니다 ...이 정적 메서드가 수행 한 작업을 수행하는 단일 목적으로 클래스를 만들었 으면 다음에서 필요한 매개 변수를 가져 와서 해결할 수 있습니다. 생성자를 통해 사용자가 속성 또는 메서드를 통해 옵션 값을 설정하여 동시에 여러 상호 의존적 인 값을 설정할 수 있습니다. 또한 메서드가이 정도의 복잡성으로 커지면

소비자에게 이유없이 클래스의 인스턴스를 생성하도록 요구

가장 일반적인 주장 중 하나는 다음과 같습니다. 우리 클래스의 소비자가이 단일 메서드를 호출하기위한 인스턴스를 생성하고 나중에 인스턴스를 사용하지 않도록 요구하는 이유는 무엇입니까? 클래스의 인스턴스를 만드는 것은 대부분의 언어에서 매우 저렴한 작업이므로 속도는 문제가되지 않습니다. 소비자에게 코드 줄을 추가하는 것은 향후 훨씬 더 유지 관리가 가능한 솔루션의 기반을 마련하기위한 저렴한 비용입니다. 마지막으로 인스턴스 생성을 피하려면 쉽게 재사용 할 수있는 클래스의 싱글 톤 래퍼를 생성하면됩니다. 그래도 클래스가 상태 비 저장이라는 요구 사항이 적용됩니다. 상태 비 저장이 아닌 경우에도 모든 것을 처리하는 정적 래퍼 메서드를 만들 수 있으며 장기적으로 모든 이점을 얻을 수 있습니다. 드디어,new MyClass();

시스 만이 절대를 다룬다

물론 정적 메서드를 싫어하는 경우에는 예외가 있습니다. 부 풀릴 위험이없는 진정한 유틸리티 클래스는 정적 메서드 (예 : System.Convert)에 대한 훌륭한 사례입니다. 프로젝트가 향후 유지 관리에 대한 요구 사항이없는 일회성 인 경우 전체 아키텍처는 실제로 매우 중요하지 않습니다 (정적이든 비 정적이든 상관 없음). 그러나 개발 속도는 중요합니다.

표준, 표준, 표준!

인스턴스 메서드를 사용한다고해서 정적 메서드를 사용할 수 없으며 그 반대의 경우도 마찬가지입니다. 차별화 뒤에 이유가 있고 표준화되어있는 한. 다양한 구현 방법으로 확장되는 비즈니스 계층을 살펴 보는 것보다 더 나쁜 것은 없습니다.


When deciding whether to make a class static or non-static you need to look at what information you are trying to represent. This entails a more 'bottom-up' style of programming where you focus on the data you are representing first. Is the class you are writing a real-world object like a rock, or a chair? These things are physical and have physical attributes such as color, weight which tells you that you may want to instantiate multiple objects with different properties. I may want a black chair AND a red chair at the same time. If you ever need two configurations at the same time then you instantly know you will want to instantiate it as an object so each object can be unique and exist at the same time.

On the other end, static functions tend to lend more to actions which do not belong to a real-world object or an object that you can easily represent. Remember that C#'s predecessors are C++ and C where you can just define global functions that do not exist in a class. This lends more to 'top-down' programming. Static methods can be used for these cases where it doesn't make sense that an 'object' performs the task. By forcing you to use classes this just makes it easier to group related functionality which helps you create more maintainable code.

Most classes can be represented by either static or non-static, but when you are in doubt just go back to your OOP roots and try to think about what you are representing. Is this an object that is performing an action (a car that can speed up, slow down, turn) or something more abstract (like displaying output).

Get in touch with your inner OOP and you can never go wrong!


For C# 3.0, extension methods may only exist in top-level static classes.


If you use code analysis tools (e.g. FxCop), it will recommend that you mark a method static if that method don't access instance data. The rationale is that there is a performance gain. MSDN: CA1822 - Mark members as static.

It is more of a guideline than a rule, really...


I do tend to use static classes for factories. For example, this is the logging class in one of my projects:

public static class Log
{
   private static readonly ILoggerFactory _loggerFactory =
      IoC.Resolve<ILoggerFactory>();

   public static ILogger For<T>(T instance)
   {
      return For(typeof(T));
   }

   public static ILogger For(Type type)
   {
      return _loggerFactory.GetLoggerFor(type);
   }
}

You might have even noticed that IoC is called with a static accessor. Most of the time for me, if you can call static methods on a class, that's all you can do so I mark the class as static for extra clarity.


Static classes are very useful and have a place, for example libraries.

The best example I can provide is the .Net Math class, a System namespace static class that contains a library of maths functions.

It is like anything else, use the right tool for the job, and if not anything can be abused.

Blankly dismissing static classes as wrong, don't use them, or saying "there can be only one" or none, is as wrong as over using the them.

C#.Net contains a number of static classes that is uses just like the Math class.

So given the correct implementation they are tremendously useful.

We have a static TimeZone class that contains a number of business related timezone functions, there is no need to create multiple instances of the class so much like the Math class it contains a set of globally accesible TimeZone realated functions (methods) in a static class.


I've started using static classes when I wish to use functions, rather than classes, as my unit of reuse. Previously, I was all about the evil of static classes. However, learning F# has made me see them in a new light.

What do I mean by this? Well, say when working up some super DRY code, I end up with a bunch of one-method classes. I may just pull these methods into a static class and then inject them into dependencies using a delegate. This also plays nicely with my dependency injection (DI) container of choice Autofac.

Of course taking a direct dependency on a static method is still usually evil (there are some non-evil uses).


I use static classes as a means to define "extra functionality" that an object of a given type could use under a specific context. Usually they turn out to be utility classes.

Other than that, I think that "Use a static class as a unit of organization for methods not associated with particular objects." describe quite well their intended usage.


This is another old but very hot question since OOP kicked in. There are many reasons to use(or not) a static class, of course and most of them have been covered in the multitude of answers.

I will just add my 2 cents to this, saying that, I make a class static, when this class is something that would be unique in the system and that would really make no sense to have any instances of it in the program. However, I reserve this usage for big classes. I never declare such small classes as in the MSDN example as "static" and, certainly, not classes that are going to be members of other classes.

I also like to note that static methods and static classes are two different things to consider. The main disadvantages mentioned in the accepted answer are for static methods. static classes offer the same flexibility as normal classes(where properties and parameters are concerned), and all methods used in them should be relevant to the purpose of the existence of the class.

A good example, in my opinion, of a candidate for a static class is a "FileProcessing" class, that would contain all methods and properties relevant for the program's various objects to perform complex FileProcessing operations. It hardly has any meaning to have more than one instance of this class and being static will make it readily available to everything in your program.


I only use static classes for helper methods, but with the advent of C# 3.0, I'd rather use extension methods for those.

I rarely use static classes methods for the same reasons why I rarely use the singleton "design pattern".


Based on MSDN:

  1. You cannot create the instance for static classes
  2. If the class declared as static, member variable should be static for that class
  3. Sealed [Cannot be Inherited]
  4. Cannot contains Instance constructor
  5. Memory Management

Example: Math calculations (math values) does not changes [STANDARD CALCULATION FOR DEFINED VALUES]

참고URL : https://stackoverflow.com/questions/241339/when-to-use-static-classes-in-c-sharp

반응형