有可能别名长代码行吗?Is it possible to alias a long code line?

- 此内容更新于:2015-01-06
主题:

下面的c#代码是在一个项目中常用的: 有什么办法可以别名这这样吗? TicketRow。背景=…;

原文:

The following line of C# code is frequently used in a project:

((DataGridRow) TicketGrid.ItemContainerGenerator.ContainerFromIndex(SelectedRow - 1)).Background = ...;

Is there any way to alias this to something like this?

TicketRow.Background = ...;
Alex K.的回复:一种财产在你? ?调用这个吗?

(原文:A property in your ?form? that calls this?)

Yuval Itzchakov的回复:也许一个属性或一个扩展方法,设置适当的值。

(原文:Perhaps a property or an extension method which sets the proper value.)

解决方案:
你可以将它在一个方法: 然后你会叫一样: SetBackground(TicketGrid…); 你总是可以把它变成一个扩展方法包装在一个静态类,使其静态和更改签名: 公共静态孔隙SetBackground(这TicketGridsType ticketGrid,PropertysType值) 然后调用 TicketGrid.SetBackground(…);
原文:

You could just wrap it in a method:

void SetBackground(TicketGridsType ticketGrid, PropertysType value)
{
    ((DataGridRow) ticketGrid.ItemContainerGenerator.ContainerFromIndex(SelectedRow - 1)).Background = value;
}

Which you would then call like so:

SetBackground(TicketGrid, ...);

You could always turn it into an extension method by wrapping it in a static class, making it static and changing the signature to:

public static void SetBackground(this TicketGridsType ticketGrid, PropertysType value)

then call

TicketGrid.SetBackground(...);
Danny Beckett的回复:我应该想到这一点!忙于跳出固有思维模式:)

(原文:I should have thought of this! Too busy trying to think outside the box :))

dav_i的回复:是的,在盒子里面坚定:)

(原文:Yep, firmly inside the box :))

Salvatore Sorbello的回复:如果你想也可以告诉编译器试图让这个方法(SetBackground)“inline"使用属性(MethodImpl(MethodImplOptions.AggressiveInlining)]在System.Runtime找到。CompilerServices名称空间

(原文:if you want you can also tell the compiler to try to make this method (SetBackground) "inline" using the attribute [MethodImpl(MethodImplOptions.AggressiveInlining)] found in the System.Runtime.CompilerServices namespace)