你使用什么 ReSharper 4 + 的 C # 实时模板?

您使用哪些针对 C # 的 ReSharper 4.0模板?

让我们以下面的格式分享这些内容:


[标题]

可选说明

快捷方式: 快捷方式
可用于: [可用性设置]

// Resharper template code snippet
// comes here

宏属性 (如有) :

  • Macro1 -值-可编辑出现
  • Macro2 -值-可编辑出现

12086 次浏览

Create new unit test fixture for some type

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

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

Macros:

  • TypeToTest - none - #2
  • Test - none - V

Create new stand-alone unit test case

Shortcut: ntc
Available in: C# 2.0+ files where type member declaration is allowed

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

Macros:

  • Test - none - V

Implement 'Dispose(bool)' Method

Implement Joe Duffy's Dispose Pattern

Shortcut: dispose

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

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;

Macros properties:

  • MEMBER - Suggest variable of System.IDisposable - Editable Occurence #1
  • CLASS - Containing type name

Create test case stub for NUnit

This one could serve as a reminder (of functionality to implement or test) that shows up in the unit test runner (as any other ignored test),

Shortcut: nts
Available in: C# 2.0+ files where type member declaration is allowed

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

Create sanity check to ensure that an argument is never null

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

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

Macros:

  • inner - Suggest parameter - #1

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

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

Assert.AreEqual

Simple template to add asserts to a unit test

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

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

Fluent version :

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

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

Invoke if Required

Useful when developing WinForms applications where a method should be callable from non-UI threads, and that method should then marshall the call onto the UI thread.

Shortcut: inv

Available in: C# 3.0+ files statement is allowed

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

Macros

  • METHOD_NAME - Containing type member name

You would normally use this template as the first statement in a given method and the result resembles:

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


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

MSTest Test Method

This is a bit lame but it's useful. Hopefully someone will get some utility out of it.

Shortcut: testMethod

Available in: C# 2.0

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


//Arrange.


//Act.


//Assert.
}


$END$

Quick ExpectedException Shortcut

Just a quick shortcut to add to my unit test attributes.

Shortcut: ee

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

[ExpectedException(typeof($TYPE$))]

Declare a log4net logger for the current type.

Shortcut: log

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

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

Macros properties:

  • TYPE - Containing type name

NUnit Setup method

Shortcut: setup
Available in: Available in: C# 2.0+ files where type member declaration is allowed

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

NUnit Teardown method

Shortcut: teardown
Available in: Available in: C# 2.0+ files where type member declaration is allowed

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

Check if variable is null

Shortcut: ifn
Available in: C# 2.0+ files

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

Check if variable is not null

Shortcut: ifnn
Available in: C# 2.0+ files

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

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

Rhino Mocks Record-Playback Syntax

Shortcut: RhinoMocksRecordPlaybackSyntax *

Available in: C# 2.0+ files

Note: This code snippet is dependent on MockRepository (var mocks = new new MockRepository();) being already declared and initialized somewhere else.

using (mocks.Record())
{
$END$
}


using (mocks.Playback())
{


}

*might seem a bit long for a shortcut name but with intellisense not an issue when typing. also have other code snippets for Rhino Mocks so fully qualifying the name makes it easier to group them together visually

Rhino Mocks Expect Methods

Shortcut: RhinoMocksExpectMethod

Available in: C# 2.0+ files

Expect.Call($EXPECT_CODE$).Return($RETURN_VALUE$);

Shortcut: RhinoMocksExpectVoidMethod

Available in: C# 2.0+ files

Expect.Call(delegate { $EXPECT_CODE$; });

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....

Borrowing from Drew Noakes excellent idea, here is an implementation of invoke for Silverlight.

Shortcut: dca

Available in: C# 3.0 files

if (!Dispatcher.CheckAccess())
{
Dispatcher.BeginInvoke((Action)delegate { $METHOD_NAME$(sender, e); });
return;
}


$END$

Macros

  • $METHOD_NAME$ non-editable name of the current containing method.

MS Test Unit Test

New MS Test Unit test using AAA syntax and the naming convention found in the Art Of Unit Testing

Shortcut: testing (or tst, or whatever you want)
Available in: C# 2.0+ files where type member declaration is allowed

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


// Act




// Assert


}

Macros properties (if present):

  • MethodName - The name of the method under test
  • StateUnderTest - The state you are trying to test
  • ExpectedBehavior - What you expect to happen

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>

New C# Guid

Generates a new System.Guid instance initialized to a new generated guid value

Shortcut: csguid Available in: in C# 2.0+ files

new System.Guid("$GUID$")

Macros properties:

  • GUID - New GUID - False

Write StyleCop-compliant summary for class constructor

(if you are tired of constantly typing in long standard summary for every constructor so it complies to StyleCop rule SA1642)

Shortcut: csum

Available in: C# 2.0+

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

Macros:

  • classname - Containing type name - V

Simple Lambda

So simple, so useful - a little lambda:

Shortcut: x

Available: C# where expression is allowed.

x => x.$END$

Macros: none.

Check if a string is null or empty.

If you're using .Net 4 you may prefer to use string.IsNullOrWhiteSpace().

Shortcut: sne

Available in: C# 2.0+ where expression is allowed.

string.IsNullOrEmpty($VAR$)

Macro properties:

  • VAR - suggest a variable of type string. Editible = true.

Notify Property Changed

This is my favourite because I use it often and it does a lot of work for me.

Shortcut: npc

Available in: C# 2.0+ where expression is allowed.

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

Macros:

  • MEMBER - Containing member type name. Not editable. Note: make sure this one is first in the list.
  • LOWEREDMEMBER - Value of MEMBER with the first character in lower case. Not editable.

Usage: Inside a property setter like this:

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

It assumes that your backing variable starts with an "_". Replace this with whatever you use. It also assumes that you have a property change method something like this:

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

In reality, the version of this I use is lambda based ('cos I loves my lambdas!) and produces the below. The principles are the same as the above.

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

That's when I'm not using the extremely elegant and useful PostSharp to do the whole INotifyPropertyChanged thing for no effort, that is.

Lots of Lambdas

Create a lambda expression with a different variable declaration for easy nesting.

Shortcut: la, lb, lc

Available in: C# 3.0+ files where expression or query clause is allowed

la is defined as:

x => x.$END$

lb is defined as:

y => y.$END$

lc is defined as:

z => z.$END$

This is similar to Sean Kearon above, except I define multiple lambda live templates for easy nesting of lambdas. "la" is most commonly used, but others are useful when dealing with expressions like this:

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

Wait for It...

Pause for user input before end of a console application.

Shortcut: pause

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

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

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; }

Machine.Specifications - Because of

As a heavy mspec user, I have several live templates specifically for MSpec. Here's a quick one for setting up a because and catching the error.

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

bece - Because of (with exception catching)

Protected static Exception exception;
Because of = () => exception = Catch.Exception(() => $something$);
$END$

AutoMapper Property Mapping

Shortcut: fm

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

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

Macros:

  • property - editable occurrence
  • src_property - editable occurrence

Note:

I leave the lambda "dot" off so that I can hit . immediately and get property intellisense. Requires AutoMapper (http://automapper.codeplex.com/).

Dependency property generation

Generates a dependency property

Shortcut: dp
Available in: C# 3.0 where member declaration is allowed

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$

Macros properties (if present):

PropertyName - No Macro - #3
PropertyType - Guess type expected at this point - #2
OwnerType - Containing type name - no editable occurence

Machine.Specifications - It

Shortcut: it

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

Machine.Specifications.It $should_$ =
() =>
{


};

Macros properties (if present):

  • should_ - (No Macro) - EditableOccurence

Equals

Neither .NET in general nor the default “equals” template make it easy to bang out a good, simple Equals method. While there are many thoughts on how to write a good Equals method, I think the following suffices for 90% of simple cases. For anything more complicated — especially when it comes to inheritance — it might be better to not use Equals at all.

Shortcut: equals
Available in: C# 2.0+ type members

public override sealed bool Equals(object other) {
return Equals(other as $TYPE$);
}


public bool Equals($TYPE$ other) {
return !ReferenceEquals(other, null) && $END$;
}


public override int GetHashCode() {
// *Always* call Equals.
return 0;
}

Macros properties:

  • TYPE - Containing type name - Not Editable