ProgramingTip

C #에서 해당하는 블록을 사용하고 있습니까?

bestdevel 2020. 11. 14. 10:57
반응형

C #에서 해당하는 블록을 사용하고 있습니까?


저는 VB.Net을 알고 있고 C #을 닦으려고합니다. C #에 해당하는 블록이 있습니까?

감사합니다


C #에는 일반적인 경우에 직접 해당하는 항목이 없지만 C # 3은 생성자 호출을위한 개체 이니셜 라이저 구문을 얻습니다.

var foo = new Foo { Property1 = value1, Property2 = value2, etc };

자세한 내용은 C # in Depth의 8 장을 참조하십시오 . Manning 웹 사이트 에서 무료로 다운로드 할 수 있습니다 .

(면책 조항-예, 더 많은 사람들의 손에 책을 전달하는 것이 제 관심사입니다.하지만 관련 주제에 대한 자세한 정보를 제공하는 무료 챕터입니다 ...)


Visual C # 프로그램 관리자는 다음과 같이 사실. C #에 'with'문이없는 이유는 무엇입니까?

C # 언어 디자이너를 포함하는 많은 사람들은 'with'가 가독성을 해치는 경우가 많으며 축복 이라기보다는 저주에 가깝다고 생각합니다. 의미있는 이름으로 지역 변수를 선언하고 그 변수를 사용하여 단일 객체에 대해 여러 작업을 수행하는 것이 제안하는 것입니다.


위에 링크 된 Visual C # 프로그램 관리자가 말했듯이 문이 더있는 상황이 있습니다. 복잡한 식에 반복적으로 액세스하기 위해 속기로 때 그가 제공하는 예입니다.

확장 방법과 제네릭을 사용하면 다음과 같이 추가하여 문과 모호하게 동등한 것을 만들 수 있습니다.

    public static T With<T>(this T item, Action<T> action)
    {
        action(item);
        return item;
    }

사용 방법에 대한 간단한 예를 들어 람다 구문을 사용하여 다음과 같이 설명 수 있습니다.

    updateRoleFamily.RoleFamilyDescription = roleFamilyDescription;
    updateRoleFamily.RoleFamilyCode = roleFamilyCode;

이에 :

    updateRoleFamily.With(rf =>
          {
              rf.RoleFamilyDescription = roleFamilyDescription;
              rf.RoleFamilyCode = roleFamilyCode;
          });

이와 같은 예제에서 유일한 장점은 더 좋은 레이아웃 일 수 있습니다 더 복잡한 참조와 더 많은 속성을 사용하면 더 읽기 쉬운 코드를 제공 할 수 있습니다.


아니 없어.


" 에서 사용하는 "섹션 에서 페이지 아래로 약 3/4 :

VB :

With hero 
  .Name = "SpamMan" 
  .PowerLevel = 3 
End With 

씨 # :

//No "With" construct
hero.Name = "SpamMan"; 
hero.PowerLevel = 3; 

인수 누산기 패턴을 사용할 수 있습니다.

여기에 대한 큰 토론 :

http://blogs.msdn.com/csharpfaq/archive/2004/03/11/87817.aspx


내가하는 일 csharp ref 키워드를 사용하는 것입니다. 예를 들면 :

ref MySubClassType e = ref MyMainClass.MySubClass;

은 다음과 당신 같은 바로 가기를 사용할 수 있습니다 e.property대신MyMainClass.MySubClass.property


가장 간단한 구문은 다음과 가변합니다.

{
    var where = new MyObject();
    where.property = "xxx";
    where.SomeFunction("yyy");
}

{
    var where = new MyObject();
    where.property = "zzz";
    where.SomeFunction("uuu");
}

이와 같은 추가 코드 블록은 변수 이름을 사용하려는 경우 매우 편리합니다.


장소 다음을 수행하여하고 있습니다.

var fill = cell.Style.Fill;
fill.PatternType = ExcelFillStyle.Solid;
fill.BackgroundColor.SetColor(Color.Gray);
fill.PatternColor = Color.Black;
fill.Gradient = ...

(EPPLus의 코드 샘플 @ http://zeeshanumardotnet.blogspot.com )


나는 이런 식으로 사용하고 있었다 :

        worksheet.get_Range(11, 1, 11, 41)
            .SetHeadFontStyle()
            .SetHeadFillStyle(45)
            .SetBorders(
                XlBorderWeight.xlMedium
                , XlBorderWeight.xlThick
                , XlBorderWeight.xlMedium
                , XlBorderWeight.xlThick)
            ;

SetHeadFontStyle / SetHeadFillStyle은 같이 범위의 ExtMethod입니다 .

 public static Range SetHeadFillStyle(this Range rng, int colorIndex)
 {
     //do some operation
     return rng;
 }

몇 가지 작업을 수행하고 다음 작업을 위해 범위반환합니다.

그것은 Linq처럼 보입니다 :)

그러나 지금은 여전히 ​​완전히 그렇게 보일 수 없습니다-적절한 설정 값

with cell.Border(xlEdgeTop)
   .LineStyle = xlContinuous
   .Weight = xlMedium
   .ColorIndex = xlAutomatic

With여기의 열혈 팬 !

이 말 그대로 현재 C # 코드입니다.

if (SKYLib.AccountsPayable.Client.ApiAuthorization.Authorization.AccessTokenExpiry == null || SKYLib.AccountsPayable.Client.ApiAuthorization.Authorization.AccessTokenExpiry < DateTime.Now)
{
    SKYLib.AccountsPayable.Client.ApiAuthorization.Authorization.Refresh();
    _api = new SKYLib.AccountsPayable.Api.DefaultApi(new SKYLib.AccountsPayable.Client.Configuration { DefaultHeader = SKYLib.AccountsPayable.Client.ApiAuthorization.Authorization.ApiHeader });
}

VB에서는 다음과 같을 수 있습니다.

With SKYLib.AccountsPayable.Client.ApiAuthorization.Authorization
    If .AccessTokenExpiry Is Nothing OrElse .AccessTokenExpiry < Now Then .Refresh()
    _api = New SKYLib.AccountsPayable.Api.DefaultApi(New SKYLib.AccountsPayable.Client.Configuration With {DefaultHeader = .ApiHeaders}
End With

훨씬 더 명확하게 생각합니다. With변수 를 조정하여 더 간결하게 수도 있습니다 . 그리고 스타일에서 여전히 선택여지가 있습니다 ! C # 프로그램 관리자가 간과 한 아마도있을 수 있습니다.

제쳐두고, 보는 것은 그리 흔하지 않지만 가끔 사용했습니다.

대신에

Using oClient As HttpClient = New HttpClient
    With oClient
        .BaseAddress = New Uri("http://mysite")
        .Timeout = New TimeSpan(123)
        .PostAsync( ... )
    End With
End Using

당신이 사용할 수있는

With New HttpClient
    .BaseAddress = New Uri("http://mysite")
    .Timeout = New TimeSpan(123)
    .PostAsync( ... )
End With

당신은 손목을 때릴 위험이 있습니다. - 그러나 Using여분의 데데 처리 등의없이 측면 에서 진술 의 모든 이점을 얻는을 구석으로 같습니다 .

참고 : 가끔 잘못 될 수 있으므로 중요하지 않은 코드에만 사용하십시오. 아니면 전혀. 기억하십시오 : 선택권이 있습니다 ...


with-pattern의 또 다른 흥미로운 구현이 있습니다.

public static T With<T>(this T o, params object[] pattern) => o;
public static T To<T>(this T o, out T x) => x = o;

링크통해 자세한 내용을 검색 하고 온라인 코드 샘플을 조사 할 수 있습니다 .

사용법의 변화

static Point Sample0() => new Point().To(out var p).With(
    p.X = 123,
    p.Y = 321,
    p.Name = "abc"
);

public static Point GetPoint() => new Point { Name = "Point Name" };
static string NameProperty { get; set; }
static string NameField;

static void Sample1()
{
    string nameLocal;
    GetPoint().To(out var p).With(
        p.X = 123,
        p.Y = 321,
        p.Name.To(out var name), /* right side assignment to the new variable */
        p.Name.To(out nameLocal), /* right side assignment to the declared var */
        NameField = p.Name, /* left side assignment to the declared variable */
        NameProperty = p.Name /* left side assignment to the property */
    );

    Console.WriteLine(name);
    Console.WriteLine(nameLocal);
    Console.WriteLine(NameField);
    Console.WriteLine(NameProperty);
}

static void Sample2() /* non-null propogation sample */
{
    ((Point)null).To(out var p)?.With(
        p.X = 123,
        p.Y = 321,
        p.Name.To(out var name)
    );

    Console.WriteLine("No exception");
}

static void Sample3() /* recursion */
{
    GetPerson().To(out var p).With(
        p.Name.To(out var name),
        p.Subperson.To(out var p0).With(
            p0.Name.To(out var subpersonName0)
        ),
        p.GetSubperson().To(out var p1).With( /* method return */
            p1.Name.To(out var subpersonName1)
        )
    );

    Console.WriteLine(subpersonName0);
    Console.WriteLine(subpersonName1);
}

고무 [값 유형]으로 작업하는 경우 놀이 확장 방법도 유용합니다.

public static TR Let<T, TR>(this T o, TR y) => y;

기본적으로 모든 것이 수정되지 않은 복사본이 제공됩니다.

struct Point
{
    public double X;
    public double Y;
    public string Name;
}

static Point Sample0() => new Point().To(out var p).With(
    p.X = 123,
    p.Y = 321,
    p.Name = "abc"
).Let(p);

즐기십시오!


"with"에 대한 closets static using이지만 정적의 메소드 또는 속성에서만 작동합니다. 예 :

using static System.Math;
...
public double Area
{
   get { return PI * Pow(Radius, 2); } // PI == System.Math.PI
}

추가 정보 : https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/using-static


흠. 나는 VB.net을 깊이 사용하지 않았기 때문에 여기서 가정하고 있지만 'using'블록이 원하는 것에 가깝다고 생각합니다.

using은 변수의 블록 범위를 정의합니다. 아래 예를 참조하세요.

using ( int temp = someFunction(param1) ) {
   temp++;  // this works fine
}

temp++; // this blows up as temp is out of scope here and has been disposed

다음은 좀 더 설명하는 Microsoft의 기사입니다.


편집 : 예,이 대답은 잘못되었습니다. 원래 가정이 잘못되었습니다. VB의 'WITH'는 새로운 C # 개체 이니셜 라이저와 비슷합니다.

var yourVariable = new yourObject { param1 = 20, param2 = "some string" };

여러 수준의 개체가있는 경우 "using"지시문으로 유사한 기능을 얻을 수 있습니다.

using System;
using GenderType = Hero.GenderType; //This is the shorthand using directive
public partial class Test : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        var myHero = new Hero();
        myHero.Name = "SpamMan";
        myHero.PowerLevel = 3;
        myHero.Gender = GenderType.Male; //instead of myHero.Gender = Hero.GenderType.Male;
    }
}
public class Hero
{
    public enum GenderType
    {
        Male,
        Female,
        Other
    }
    public string Name;
    public int PowerLevel;
    public GenderType Gender;
}

참고 URL : https://stackoverflow.com/questions/481725/with-block-equivalent-in-c

반응형