我已经实现了一个使用TextRenderer.DrawText的CellPainting事件处理程序,它已经很好地工作,直到一个单元格中有一个&符号.单元格在编辑单元格时正确显示&符号,但是在完成编辑并绘制它时,它会显示为一条小线(不是下划线).

using System;
using System.Drawing;
using System.Windows.Forms;
namespace StackOverFlowFormExample {
public partial class DataGridViewImplementation : DataGridView {
public DataGridViewImplementation() {
InitializeComponent();
this.ColumnCount = 1;
this.CellPainting += DGV_CellPainting;
}
private void DGV_CellPainting(object sender, DataGridViewCellPaintingEventArgs e) {
if (!e.Handled && e.RowIndex > -1 && e.Value != null) {
e.PaintBackground(e.CellBounds, false);
TextRenderer.DrawText(e.Graphics, e.Value.ToString(),
e.CellStyle.Font, e.CellBounds,
e.CellStyle.ForeColor, TextFormatFlags.VerticalCenter);
e.Handled = true;
}
}
}
}
//creating the datagridview
public partial class MainForm : Form {
public MainForm() {
InitializeComponent();
DataGridViewImplementation dgvi = new DataGridViewImplementation(); …Run Code Online (Sandbox Code Playgroud) 目标: ForEach扩展掩蔽选择.
原因:选择允许方法链接,而foreach没有; ForEach比Select更具可读性.
我遇到的问题是我收到了这个错误.
无法从用法推断出方法'System.Linq.Enumerable.Select(System.Collections.Generic.IEnumerable,System.Func)'的类型参数.尝试显式指定类型参数.(CS0411)
public static void ForEach<T>(this IEnumerable<T> elements, Action<T, int> action)
{
elements.Select((elem, i) => action(elem, i));
}
Run Code Online (Sandbox Code Playgroud)
我尝试过,elements.Select((T elem, int i) => action(elem, i));但产生同样的错误.
我也尝试使用Func而不是Action,但似乎没有任何方法可以使用void来返回(无论如何都是Action).如果我定义采用Func而不是Action的方法,那么当我尝试使用Action调用它时,我会得到相同的错误.
public static IEnumerable<TOut> ForEach<TIn, TOut>(this IEnumerable<TIn> elements,
Func<TIn, int, TOut> function)
{
return elements.Select((elem, i) => function(elem, i))
.ToList();
}
Run Code Online (Sandbox Code Playgroud)
我不明白哪些论据无法推断.我有办法解决这个问题(使用for循环或foreach循环并跟踪索引),但我仍然想知道为什么这不起作用.
编辑:当我从foreach循环切换到调用Select时,我也意识到我的其他ForEach for Action(没有索引)也会出现此错误.
public static void ForEach<T>(this IEnumerable<T> elements, Action<T> action)
{
elements.ToList().Select((T elem) => action(elem));
/*foreach (var elem in elements)
action(elem);*/
}
Run Code Online (Sandbox Code Playgroud)