program story

어떤 C # 용 ReSharper 4+ 라이브 템플릿을 사용하십니까?

inputbox 2020. 8. 28. 07:25
반응형

어떤 C # 용 ReSharper 4+ 라이브 템플릿을 사용하십니까? [닫은]


어떤 C # 용 ReSharper 4.0 템플릿을 사용하십니까?

다음 형식으로 공유해 보겠습니다.


[표제]

선택적 설명

바로 가기 : 바로 가기
사용 가능 : [AvailabilitySetting]

// Resharper template code snippet
// comes here

매크로 속성 (있는 경우) :

  • Macro1--EditableOccurence
  • Macro2--EditableOccurence


간단한 람다

매우 간단하고 유용합니다-약간의 람다 :

바로 가기 : x

사용 가능 :식이 허용되는 C #입니다.

x => x.$END$

매크로 : 없음.


'Dispose (bool)'메서드 구현

Joe Duffy의 Dispose 패턴 구현

바로 가기 : 폐기

사용 가능 : 유형 멤버 선언이 허용되는 C # 2.0+ 파일

public void Dispose()
{
    Dispose(true);
    System.GC.SuppressFinalize(this);
}

protected virtual void Dispose(bool disposing)
{
    if (!disposed)
    {
        if (disposing)
        {
            if ($MEMBER$ != null)
            {
                $MEMBER$.Dispose();
                $MEMBER$ = null;
            }
        }

        disposed = true;
    }
}

~$CLASS$()
{
    Dispose(false);
}

private bool disposed;

매크로 속성 :

  • MEMBER -System.IDisposable의 변수 제안-편집 가능한 발생 # 1
  • CLASS- 포함 유형 이름

일부 유형에 대한 새 단위 테스트 픽스처 생성

바로 가기 : ntf
사용 가능 : 형식 멤버 선언 또는 네임 스페이스 선언이 허용되는 C # 2.0+ 파일

[NUnit.Framework.TestFixtureAttribute]
public sealed class $TypeToTest$Tests
{
    [NUnit.Framework.TestAttribute]
    public void $Test$()
    {
        var t = new $TypeToTest$()
        $END$
    }
}

매크로 :

  • TypeToTest- 없음-# 2
  • 테스트 -없음-V

문자열이 null인지 비어 있는지 확인합니다.

.Net 4를 사용하는 경우 string.IsNullOrWhiteSpace ()를 사용하는 것이 좋습니다.

바로 가기 : sne

사용 가능 :식이 허용되는 C # 2.0+.

string.IsNullOrEmpty($VAR$)

매크로 속성 :

  • VAR-문자열 유형의 변수를 제안합니다. 편집 가능 = 사실.

새로운 독립형 단위 테스트 케이스 만들기

바로 가기 : ntc
사용 가능 : 형식 멤버 선언이 허용되는 C # 2.0+ 파일

[NUnit.Framework.TestAttribute]
public void $Test$()
{
    $END$
}

매크로 :

  • 테스트 -없음-V

현재 유형에 대한 log4net 로거를 선언하십시오.

바로 가기 : 로그

사용 가능 : 유형 멤버 선언이 허용되는 C # 2.0+ 파일

private static readonly log4net.ILog log = log4net.LogManager.GetLogger(typeof($TYPE$));

매크로 속성 :

  • TYPE - 유형 이름을 포함하는

MS 테스트 단위 테스트

AAA 구문과 Art Of Unit Testing 에있는 명명 규칙을 사용하는 새로운 MS 테스트 단위 테스트

바로 가기 : 테스트 (또는 tst 또는 원하는대로)
사용 가능 : 유형 멤버 선언이 허용되는 C # 2.0+ 파일

[TestMethod]
public void $MethodName$_$StateUnderTest$_$ExpectedBehavior$()
{
    // Arrange
    $END$

    // Act


    // Assert

}

매크로 속성 (있는 경우) :

  • MethodName- 테스트중인 메소드의 이름
  • StateUnderTest- 테스트하려는 상태
  • ExpectedBehavior- 예상되는 일

변수가 null인지 확인

바로 가기 : ifn
사용 가능 : C # 2.0+ 파일

if (null == $var$)
{
    $END$
}

변수가 null이 아닌지 확인

바로 가기 : ifnn
사용 가능 : C # 2.0+ 파일

if (null != $var$)
{
    $END$
}

클래스 생성자에 대한 StyleCop 호환 요약 작성

(모든 생성자에 대해 긴 표준 요약을 지속적으로 입력하는 데 지쳐서 StyleCop 규칙 SA1642를 준수하는 경우)

바로 가기 : csum

사용 가능 : C # 2.0+

Initializes a new instance of the <see cref="$classname$"/> class.$END$

매크로 :

  • classname- 포함 유형 이름-V

Assert.AreEqual

단위 테스트에 어설 션을 추가하는 간단한 템플릿

바로 가기 : ae
사용 가능 : C # 2.0+ 파일에서 문이 허용되는 파일

Assert.AreEqual($expected$, $actual$);$END$

유창한 버전 :

Assert.That($expected$, Is.EqualTo($actual$));$END$

많은 람다

쉬운 중첩을 위해 다른 변수 선언으로 람다 식을 만듭니다.

바로 가기 : la, lb, lc

사용 가능 : 식 또는 쿼리 절이 허용되는 C # 3.0+ 파일

la 는 다음과 같이 정의됩니다.

x => x.$END$

lb 는 다음과 같이 정의됩니다.

y => y.$END$

lc 는 다음과 같이 정의됩니다.

z => z.$END$

람다를 쉽게 중첩 할 수 있도록 여러 개의 람다 라이브 템플릿을 정의한다는 점을 제외하면 위의 Sean Kearon과 비슷합니다. " la "가 가장 일반적으로 사용되지만 다음과 같은 표현식을 처리 할 때 다른 것들이 유용합니다.

items.ForEach(x => x.Children.ForEach(y => Console.WriteLine(y.Name)));

좀 기다려...

콘솔 응용 프로그램이 종료되기 전에 사용자 입력을 위해 일시 ​​중지합니다.

바로 가기 : 일시 중지

사용 가능 : 문이 허용되는 C # 2.0+ 파일

System.Console.WriteLine("Press <ENTER> to exit...");
System.Console.ReadLine();$END$

종속성 속성 생성

종속성 속성을 생성합니다.

바로 가기 : dp
사용 가능 : 멤버 선언이 허용되는 C # 3.0

public static readonly System.Windows.DependencyProperty $PropertyName$Property =
        System.Windows.DependencyProperty.Register("$PropertyName$",
                                                   typeof ($PropertyType$),
                                                   typeof ($OwnerType$));

    public $PropertyType$ $PropertyName$
    {
        get { return ($PropertyType$) GetValue($PropertyName$Property); }
        set { SetValue($PropertyName$Property, value); }
    }

$END$

매크로 속성 (있는 경우) :

PropertyName-매크로 없음-# 3
PropertyType-이 시점에서 예상되는 유형 추측-# 2
OwnerType-유형 이름 포함-편집 가능한 발생 없음


속성 변경 알림

자주 사용하고 많은 작업을 수행하기 때문에 이것이 제가 가장 좋아하는 것입니다.

바로 가기 : npc

사용 가능 :식이 허용되는 C # 2.0+.

if (value != _$LOWEREDMEMBER$)
{
  _$LOWEREDMEMBER$ = value;
  NotifyPropertyChanged("$MEMBER$");
}

매크로 :

  • MEMBER-멤버 유형 이름 포함. 편집 할 수 없습니다. 참고 : 이것이 목록에서 첫 번째인지 확인하십시오.
  • LOWEREDMEMBER-첫 번째 문자가 소문자 인 MEMBER의 값입니다. 편집 할 수 없습니다.

사용법 : 다음과 같은 속성 setter 내부 :

private string _dateOfBirth;
public string DateOfBirth
{
   get { return _dateOfBirth; }
   set
   {
      npc<--tab from here
   }
}

지원 변수가 "_"로 시작한다고 가정합니다. 이것을 사용하는 것으로 교체하십시오. 또한 다음과 같은 속성 변경 메서드가 있다고 가정합니다.

private void NotifyPropertyChanged(String info)
{
   if (PropertyChanged != null)
   {
      PropertyChanged(this, new PropertyChangedEventArgs(info));
   }
}

실제로 내가 사용하는 버전은 람다 기반이며 ( '내가 내 람다를 좋아하기 때문에!) 다음을 생성합니다. 원칙은 위와 동일합니다.

public decimal CircuitConductorLive
{
   get { return _circuitConductorLive; }
   set { Set(x => x.CircuitConductorLive, ref _circuitConductorLive, value); }
}

그것은 내가 매우 우아하고 유용한 PostSharp를 사용하여 노력하지 않고 전체 INotifyPropertyChanged 일을 수행하지 않을 때입니다.


빠른 ExpectedException 바로 가기

내 단위 테스트 속성에 추가하는 바로 가기입니다.

바로 가기 : ee

사용 가능 : 사용 가능 : 유형 멤버 선언이 허용되는 C # 2.0+ 파일

[ExpectedException(typeof($TYPE$))]

AutoMapper 속성 매핑

단축키 : fm

사용 가능 : 문이 허용되는 C # 2.0+ 파일

.ForMember(d => d$property$, o => o.MapFrom(s => s$src_property$))
$END$

매크로 :

  • 속성-편집 가능한 발생
  • src_property-편집 가능한 발생

노트 :

나는를 칠 수 있도록 람다 "점"을 제거합니다. 즉시 재산 정보를 얻으십시오. AutoMapper ( http://automapper.codeplex.com/ )가 필요합니다 .


NUnit 용 테스트 케이스 스텁 만들기

이것은 단위 테스트 실행기 (다른 무시 된 테스트와 마찬가지로)에 표시되는 알림 (구현 또는 테스트 할 기능)의 역할을 할 수 있습니다.

바로 가기 : nts
사용 가능 : 형식 멤버 선언이 허용되는 C # 2.0+ 파일

[Test, Ignore]
public void $TestName$()
{
    throw new NotImplementedException();
}
$END$

필요한 경우 호출

UI가 아닌 스레드에서 메서드를 호출 할 수 있어야하고 해당 메서드가 호출을 UI 스레드로 마샬링해야하는 WinForms 응용 프로그램을 개발할 때 유용합니다.

바로 가기 : inv

사용 가능 : C # 3.0+ 파일 문 허용

if (InvokeRequired)
{
    Invoke((System.Action)delegate { $METHOD_NAME$($END$); });
    return;
}

매크로

  • METHOD_NAME- 유형 멤버 이름 포함

일반적으로이 템플릿을 주어진 메서드의 첫 번째 문으로 사용하며 결과는 다음과 같습니다.

void DoSomething(Type1 arg1)
{
    if (InvokeRequired)
    {
        Invoke((Action)delegate { DoSomething(arg1); });
        return;
    }

    // Rest of method will only execute on the correct thread
    // ...
}

새로운 C # Guid

새로 생성 된 guid 값으로 초기화 된 새 System.Guid 인스턴스를 생성합니다.

바로 가기 : csguid 사용 가능 : C # 2.0+ 파일

new System.Guid("$GUID$")

매크로 속성 :

  • GUID- 새 GUID-False

MSTest 테스트 방법

이것은 약간 절름발이지만 유용합니다. 누군가가 그것으로부터 약간의 유용성을 얻을 수 있기를 바랍니다.

바로 가기 : testMethod

사용 가능 : C # 2.0

[TestMethod]
public void $TestName$()
{
    throw new NotImplementedException();

    //Arrange.

    //Act.

    //Assert.
}

$END$

NUnit 설정 방법

바로 가기 : 설정
사용 가능 : 사용 가능 : 유형 멤버 선언이 허용되는 C # 2.0+ 파일

[NUnit.Framework.SetUp]
public void SetUp()
{
    $END$
}

NUnit 분해 방법

바로 가기 : 분해
사용 가능 : 사용 가능 : 유형 멤버 선언이 허용되는 C # 2.0+ 파일

[NUnit.Framework.TearDown]
public void TearDown()
{
    $END$
}

인수가 null이 아닌지 확인하기 위해 온 전성 검사를 만듭니다.

바로 가기 : eann
사용 위치 : 유형 문이 허용되는 C # 2.0+ 파일

Enforce.ArgumentNotNull($inner$, "$inner$");

매크로 :

  • inner - Suggest parameter - #1

Remarks: Although this snippet targets open source .NET Lokad.Shared library, it could be easily adapted to any other type of argument check.


New COM Class

Shortcut: comclass

Available in: C# 2.0+ files where type member declaration or namespace declaration is allowed

[ComVisible(true)]
[ClassInterface(ClassInterfaceType.None)]
[Guid("$GUID$")]
public class $NAME$ : $INTERFACE$
{
    $END$
}

Macros

  • GUID - New GUID
  • NAME - Editable
  • INTERFACE - Editable

Assert Invoke Not Required

Useful when developing WinForms applications where you want to be sure that code is executing on the correct thread for a given item. Note that Control implements ISynchronizeInvoke.

Shortcut: ani

Available in: C# 2.0+ files statement is allowed

Debug.Assert(!$SYNC_INVOKE$.InvokeRequired, "InvokeRequired");

Macros

  • SYNC_INVOKE - Suggest variable of System.ComponentModel.ISynchronizeInvoke

Trace - Writeline, with format

Very simple template to add a trace with a formatted string (like Debug.WriteLine supports already).

Shortcut: twlf
Available in: C# 2.0+ files where statement is allowed

Trace.WriteLine(string.Format("$MASK$",$ARGUMENT$));

Macros properties:

  • Argument - value - EditableOccurence
  • Mask - "{0}" - EditableOccurence

New Typemock isolator fake

Shortcut: fake
Available in: [in c# 2.0 files where statement is allowed]

$TYPE$ $Name$Fake = Isolate.Fake.Instance();
Isolate.WhenCalled(() => $Name$Fake.)

Macros properties:
* $TYPE$ - Suggest type for a new variable
* $Name$ - Value of another variable (Type) with the first character in lower case


Since I'm working with Unity right now, I've come up with a few to make my life a bit easier:


Type Alias

Shortcut: ta
Available in: *.xml; *.config

<typeAlias alias="$ALIAS$" type="$TYPE$,$ASSEMBLY$"/>

Type Declaration

This is a type with no name and no arguments

Shortcut: tp
Available in: *.xml; *.config

<type type="$TYPE$" mapTo="$MAPTYPE$"/>

Type Declaration (with name)

This is a type with name and no arguments

Shortcut: tn
Available in: *.xml; *.config

<type type="$TYPE$" mapTo="$MAPTYPE$" name="$NAME$"/>

Type Declaration With Constructor

This is a type with name and no arguments

Shortcut: tpc
Available in: *.xml; *.config

<type type="$TYPE$" mapTo="$MAPTYPE$">
  <typeConfig>
    <constructor>
        $PARAMS$
    </constructor>
  </typeConfig>
</type>

etc....


log4net XML Configuration Block

You can import the template directly:

<TemplatesExport family="Live Templates">
  <Template uid="49c599bb-a1ec-4def-a2ad-01de05799843" shortcut="log4" description="inserts log4net XML configuration block" text="  &lt;configSections&gt;&#xD;&#xA;    &lt;section name=&quot;log4net&quot; type=&quot;log4net.Config.Log4NetConfigurationSectionHandler,log4net&quot; /&gt;&#xD;&#xA;  &lt;/configSections&gt;&#xD;&#xA;&#xD;&#xA;  &lt;log4net debug=&quot;false&quot;&gt;&#xD;&#xA;    &lt;appender name=&quot;LogFileAppender&quot; type=&quot;log4net.Appender.RollingFileAppender&quot;&gt;&#xD;&#xA;      &lt;param name=&quot;File&quot; value=&quot;logs\\$LogFileName$.log&quot; /&gt;&#xD;&#xA;      &lt;param name=&quot;AppendToFile&quot; value=&quot;false&quot; /&gt;&#xD;&#xA;      &lt;param name=&quot;RollingStyle&quot; value=&quot;Size&quot; /&gt;&#xD;&#xA;      &lt;param name=&quot;MaxSizeRollBackups&quot; value=&quot;5&quot; /&gt;&#xD;&#xA;      &lt;param name=&quot;MaximumFileSize&quot; value=&quot;5000KB&quot; /&gt;&#xD;&#xA;      &lt;param name=&quot;StaticLogFileName&quot; value=&quot;true&quot; /&gt;&#xD;&#xA;&#xD;&#xA;      &lt;layout type=&quot;log4net.Layout.PatternLayout&quot;&gt;&#xD;&#xA;        &lt;param name=&quot;ConversionPattern&quot; value=&quot;%date [%3thread] %-5level %-40logger{3} - %message%newline&quot; /&gt;&#xD;&#xA;      &lt;/layout&gt;&#xD;&#xA;    &lt;/appender&gt;&#xD;&#xA;&#xD;&#xA;    &lt;appender name=&quot;ConsoleAppender&quot; type=&quot;log4net.Appender.ConsoleAppender&quot;&gt;&#xD;&#xA;      &lt;layout type=&quot;log4net.Layout.PatternLayout&quot;&gt;&#xD;&#xA;        &lt;param name=&quot;ConversionPattern&quot; value=&quot;%message%newline&quot; /&gt;&#xD;&#xA;      &lt;/layout&gt;&#xD;&#xA;    &lt;/appender&gt;&#xD;&#xA;&#xD;&#xA;    &lt;root&gt;&#xD;&#xA;      &lt;priority value=&quot;DEBUG&quot; /&gt;&#xD;&#xA;      &lt;appender-ref ref=&quot;LogFileAppender&quot; /&gt;&#xD;&#xA;    &lt;/root&gt;&#xD;&#xA;  &lt;/log4net&gt;&#xD;&#xA;" reformat="False" shortenQualifiedReferences="False">
    <Context>
      <FileNameContext mask="*.config" />
    </Context>
    <Categories />
    <Variables>
      <Variable name="LogFileName" expression="getOutputName()" initialRange="0" />
    </Variables>
    <CustomProperties />
  </Template>
</TemplatesExport>

Make Method Virtual

Adds virtual keyword. Especially useful when using NHibernate, EF, or similar framework where methods and/or properties must be virtual to enable lazy loading or proxying.

Shortcut: v

Available in: C# 2.0+ file where type member declaration is allowed

virtual $END$

The trick here is the space after virtual, which might be hard to see above. The actual template is "virtual $END$" with reformat code enabled. This allows you to go to the insert point below (denoted by |) and type v:

public |string Name { get; set; }

참고URL : https://stackoverflow.com/questions/186970/what-resharper-4-live-templates-for-c-sharp-do-you-use

반응형