问题
What ReSharper 4.0 templates for C# do you use?
Let's share these in the following format:
[Title]
Optional description
Shortcut: shortcut
Available in: [AvailabilitySetting]
// Resharper template code snippet
// comes here
Macros properties (if present):
- Macro1 - Value - EditableOccurence
- Macro2 - Value - EditableOccurence
- One macro per answer, please!
- Here are some samples for NUnit test fixture and Standalone NUnit test case that describe live templates in the suggested format.
回答1:
Simple Lambda
So simple, so useful - a little lambda:
Shortcut: x
Available: C# where expression is allowed.
x => x.$END$
Macros: none.
回答2:
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
回答3:
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
回答4:
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.
回答5:
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
回答6:
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
回答7:
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
回答8:
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$
}
回答9:
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
回答10:
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$
回答11:
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)));
回答12:
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$
回答13:
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
回答14:
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.
回答15:
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$))]
回答16:
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/).
回答17:
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$
回答18:
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
// ...
}
回答19:
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
回答20:
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$
回答21:
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$
}
回答22:
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$
}
回答23:
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
Remarks: Although this snippet targets open source .NET Lokad.Shared library, it could be easily adapted to any other type of argument check.
回答24:
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
回答25:
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
回答26:
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
回答27:
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
回答28:
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....
回答29:
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=" <configSections>
 <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" />
 </configSections>

 <log4net debug="false">
 <appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender">
 <param name="File" value="logs\\$LogFileName$.log" />
 <param name="AppendToFile" value="false" />
 <param name="RollingStyle" value="Size" />
 <param name="MaxSizeRollBackups" value="5" />
 <param name="MaximumFileSize" value="5000KB" />
 <param name="StaticLogFileName" value="true" />

 <layout type="log4net.Layout.PatternLayout">
 <param name="ConversionPattern" value="%date [%3thread] %-5level %-40logger{3} - %message%newline" />
 </layout>
 </appender>

 <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
 <layout type="log4net.Layout.PatternLayout">
 <param name="ConversionPattern" value="%message%newline" />
 </layout>
 </appender>

 <root>
 <priority value="DEBUG" />
 <appender-ref ref="LogFileAppender" />
 </root>
 </log4net>
" reformat="False" shortenQualifiedReferences="False">
<Context>
<FileNameContext mask="*.config" />
</Context>
<Categories />
<Variables>
<Variable name="LogFileName" expression="getOutputName()" initialRange="0" />
</Variables>
<CustomProperties />
</Template>
</TemplatesExport>
回答30:
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; }
来源:https://stackoverflow.com/questions/186970/what-resharper-4-live-templates-for-c-sharp-do-you-use