如何使此 C# 函数可重用

本文关键字:函数 何使此 | 更新日期: 2023-09-27 18:34:05

我正在使用在这篇文章中提供的datagridview中格式化时间戳的代码:

设置数据网格视图列中的时间跨度格式

。而且我对要添加到datagridview_Cellformatting事件中的代码有问题。

这是有问题的代码:

private void dataGridView_CellFormatting(object sender, 
                                       DataGridViewCellFormattingEventArgs e)
{
    var formatter = e.CellStyle.FormatProvider as ICustomFormatter;
    if (formatter != null)
    {
        e.Value = formatter.Format(e.CellStyle.Format, 
                                   e.Value, 
                                   e.CellStyle.FormatProvider);
        e.FormattingApplied = true;
    }
}

这很好用,但我的问题是,鉴于我在应用程序中执行的数据绑定的性质,我需要在十个不同的 datagridview 对象上调用此方法。

您会注意到此方法捕获事件目标,这意味着我当前在代码中使用此方法的十个单独副本。必须有一种方法可以将其合并为一个方法,我可以从 CellFormatting 事件上的任何数据网格视图中调用该方法。

有谁知道这是怎么做到的?

如何使此 C# 函数可重用

with extensions method。

namespace Foo 
{
    public static class DataGridExtensions
    {
        public static void FormatViewCell(this DataGridViewCellFormattingEventArgs e)
        {
            var formatter = e.CellStyle.FormatProvider as ICustomFormatter;
            if (formatter != null)
            {
                e.Value = formatter.Format(e.CellStyle.Format, 
                                           e.Value, 
                                           e.CellStyle.FormatProvider);
                e.FormattingApplied = true;
            }
        }
    }
}

在数据网格上 单元格格式

using Foo;
private void dataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    e.FormatViewCell();
}

可以使用存储在帮助程序类中的静态方法,如下所示:

private static void AddCellFormatting(DataGridView dgView)
{
    dgView.CellFormatting += (sender, e) => 
    {
        var formatter = e.CellStyle.FormatProvider as ICustomFormatter;
        if (formatter != null)
        {
            e.Value = formatter.Format(e.CellStyle.Format, e.Value, e.CellStyle.FormatProvider);
            e.FormattingApplied = true;
        }
    }
}

该方法可以在 InitializeComponent() 之后从构造函数调用。

或者干脆将您的方法用作静态方法并从设计器添加它。