2

I'm trying to write a vs code snippet that will take the selected and surround it with an if null check, i.e.

accgrp.CREATEDATE = DateTime.Now;

will become:

if (accgrp.CREATEDATE == null)
        {
            accgrp.CREATEDATE = DateTime.Now;
        }

I've got as far as the below. $selected$ only seems to work the last time it is used, if used more than once, the other instances where you would expected to see the selected code are blank. I understand the code below wouldn't do exactly what I want, as I wont get the right hand side of the assignment, btu it would be good enough.

            <Declarations>
            <Literal>
                <ID>expression</ID>
                <ToolTip>Expression to evaluate</ToolTip>
                <Default>o</Default>
            </Literal>
        </Declarations>
        <Code Language="csharp"><![CDATA[if ($selected$ == null)
{
    $selected$ = $expression$$end$   
}]]>
        </Code>

Can anyone help?

4

2 回答 2

1

Assuming CREATEDATE is a property, why don't you move this logic over there?

DateTime? CREATEDATE
{
    set { _createdate = value ?? DateTime.Now; }
}

or use the same ?? operator outside setter:

accgrp.CREATEDATE = accgrp.CREATEDATE ?? DateTime.Now;
于 2009-04-21T11:54:09.010 回答
1

Here is macro for you, that will provide you identical functionality.

Sub NullCheck()
    Dim selected As String
    Dim var As String
    Dim res As String
    Dim sel As TextSelection


    sel = DTE.ActiveDocument.Selection
    selected = sel.Text        
    var = selected.Substring(0, selected.IndexOf("=") - 1).Trim()
    res = String.Format("if ({0} == null) {1} ", var, selected)

    sel.Delete()
    sel.Insert(res, vsInsertFlags.vsInsertFlagsContainNewText)
    sel.SmartFormat()

End Sub

The alternative (after reading your comment) may be to use PostSharp in order to intercept field/property setter.

于 2009-04-21T12:07:34.797 回答