정적 코드 블록
에서가는 Java
에 C#
내가 다음을 수행 할 수있는 자바에서 : 나는 다음과 같은 질문이 있습니다 :
public class Application {
static int attribute;
static {
attribute = 5;
}
// ... rest of code
}
나는 이것을 생성자에서 초기화 할 수 있다는 것을 알고 있지만 이것은 내 요구에 맞지 않습니다 (객체를 만들지 않고 일부 유틸리티 함수를 초기화하고 호출하고 싶습니다). C #이이를 지원합니까? 그렇다면 어떻게해야합니까?
미리 감사드립니다.
public class Application()
{
static int attribute;
static Application()
{
attribute = 5;
} // ..... rest of code
}
C #에 해당하는 정적 생성자를 사용할 수 있습니다 . 일반 생성자와 혼동하지 마십시오. 일반 생성자는 static
앞에 수정자가 없습니다 .
나는 당신의 //... rest of the code
필요가 또한 한 번 실행되어야 한다고 가정하고 있습니다 . 이러한 코드가 없으면 간단히 이렇게 할 수 있습니다.
public class Application()
{
static int attribute = 5;
}
다음과 같이 정적 생성자 블록을 작성할 수 있습니다.
static Application(){
attribute=5;
}
이것이 제가 생각할 수있는 것입니다.
특정 시나리오에서 다음을 수행 할 수 있습니다.
public class Application {
static int attribute = 5;
// ... rest of code
}
최신 정보:
정적 메서드를 호출하려는 것 같습니다. 다음과 같이 할 수 있습니다.
public static class Application {
static int attribute = 5;
public static int UtilityMethod(int x) {
return x + attribute;
}
}
다른 유용한 것이 있습니다. 변수를 초기화하는 데 둘 이상의 표현식 / 문이 필요하면 이것을 사용하십시오!
static A a = new Func<A>(() => {
// do it here
return new A();
})();
이 접근 방식은 클래스에만 국한되지 않습니다.
-정적 생성자에는 매개 변수가 없습니다.
-정적 클래스는 하나의 정적 생성자 만 포함 할 수 있습니다.
-프로그램을 실행할 때 정적 생성자가 먼저 실행됩니다.
예:
namespace InterviewPreparation
{
public static class Program
{ //static Class
static Program()
{ //Static constructor
Console.WriteLine("This is static consturctor.");
}
public static void Main()
{ //static main method
Console.WriteLine("This is main function.");
Console.ReadKey();
}
}
}
출력 :
이것은 정적 생성자입니다.
이것이 주요 기능입니다.
참고 URL : https://stackoverflow.com/questions/8459095/static-code-blocks
'developer tip' 카테고리의 다른 글
HTML5 사용의 요점 (0) | 2020.11.27 |
---|---|
JavaScript에서 &와 &&의 차이점은 무엇입니까? (0) | 2020.11.27 |
C ++ 참조로 배열 전달 (0) | 2020.11.27 |
모카의 글로벌`before`와`beforeEach`? (0) | 2020.11.27 |
정규 표현식으로 겹치는 일치를 찾는 방법은 무엇입니까? (0) | 2020.11.27 |