C# 获取列索引作为常量值

C# 获取列索引作为常量值,c#,datagridview,switch-statement,C#,Datagridview,Switch Statement,目前,我在dataGridView1\u CellValidating事件中有这样的代码: if(e.ColumnIndex == dataGridView1.Columns["FIRST"].Index) { // Some code } else if(e.ColumnIndex == dataGridView1.Columns["Second"].Index) { // Some code } else if(e.ColumnIndex == dataGridView1.C

目前,我在
dataGridView1\u CellValidating
事件中有这样的代码:

if(e.ColumnIndex == dataGridView1.Columns["FIRST"].Index)
{
    // Some code
}
else if(e.ColumnIndex == dataGridView1.Columns["Second"].Index)
{
    // Some code
}
else if(e.ColumnIndex == dataGridView1.Columns["Third"].Index)
{
    // Some code
}
它是这样的,因为我不能在switch语句中使用它,比如:

switch(e.ColumnIndex)
{
    case dataGridView.Columns["First"].Index:
        break;
    case dataGridView.Columns["Second"].Index:
        break;
    case dataGridView.Columns["Third"].Index:
        break;
}
大小写
上返回错误,该行应为常量值


那么我如何才能做到这一点呢?

如果你真的想使用switch,你可以在switch case中使用模式匹配

注:适用于C#7.0或以上

switch(e.ColumnIndex)
{
    case var _ when (dataGridView.Columns["First"].Index == e.ColumnIndex):
        break;
    case var _ when (dataGridView.Columns["Second"].Index == e.ColumnIndex):
        break;
    case var _ when (dataGridView.Columns["Third"].Index == e.ColumnIndex):
        break;
}

如果您真的想使用switch,您可以在switch case中使用模式匹配

注:适用于C#7.0或以上

switch(e.ColumnIndex)
{
    case var _ when (dataGridView.Columns["First"].Index == e.ColumnIndex):
        break;
    case var _ when (dataGridView.Columns["Second"].Index == e.ColumnIndex):
        break;
    case var _ when (dataGridView.Columns["Third"].Index == e.ColumnIndex):
        break;
}

也许,您可以先设置常量值,然后为其指定dataGridView.Columns[“first”].Index。 例如:

int a = {given index}
const int IndexOfFirstCol = dataGridView.Columns["First"].Index;
const int IndexOfSecCol = dataGridView.Columns["Second"].Index;
那么


也许,您可以先设置常量值,然后为其指定dataGridView.Columns[“first”].Index。 例如:

int a = {given index}
const int IndexOfFirstCol = dataGridView.Columns["First"].Index;
const int IndexOfSecCol = dataGridView.Columns["Second"].Index;
那么


我会有另一种方法,使用以这种方式构建的方法的
Dictionnary
(来自名称空间
System.Collections.Generic

键是datagridview中列的索引(“第一”、“第二”…)

该值是要执行的方法的委托(在每个if/else if中,什么将替换您的
//某些代码

例如:

/*
 * This example is written for console application, that can be tested easily.
 * The logic can be rewritten for WinForm
 */

static void TheFirstCase()
{
    //This should be replaced by the differents actions you want to do
    Console.WriteLine("first case"); 
}

static void TheSecondtCase()
{
    Console.WriteLine("second case");
}

static void TheThirdCase()
{
    Console.WriteLine("third case");
}

static void Main(string[] args)
{
    Dictionary<string, Delegate> MyDic = new Dictionary<string, Delegate>
    {
        //If you need parameters in the TheFirstCase(), use new Action<TypeOfTheFirstParam, TypeOfTheSecondParam, ...>(TheFirstCase)
        //If your Method needs to return something, use Func instead of Action
        { "First", new Action(TheFirstCase) }, 
        { "Second", new Action(TheSecondtCase) },
        { "Third", new Action(TheThirdCase) }
    };
    // in your question, this is e.ColumnIndex
    var ValueInColIndex = 42;

    // in your question, this is dataGridView.Columns
    var DataGridViewDatas = new Dictionary<string, int>
    {
        {  "First", 0 },
        {  "Second", 42 },
        {  "Third", 69 }
    };

    foreach (var MyAction in MyDic)
    {
        if (DataGridViewDatas[MyAction.Key] == ValueInColIndex)
        {
            MyAction.Value.DynamicInvoke();
        }
    }
}
/*
*这个例子是为控制台应用程序编写的,可以很容易地进行测试。
*可以为WinForm重写逻辑
*/
静态作废第一个案例()
{
//这应该被您想要执行的不同操作所取代
控制台写入线(“第一个案例”);
}
静态无效第二种情况()
{
Console.WriteLine(“第二种情况”);
}
静态无效第三种情况()
{
Console.WriteLine(“第三种情况”);
}
静态void Main(字符串[]参数)
{
字典MyDic=新字典
{
//如果在TheFirstCase()中需要参数,请使用新操作(TheFirstCase)
//如果您的方法需要返回某些内容,请使用Func而不是Action
{“第一”,新行动(第一种情况)},
{“第二”,新动作(第二幕)},
{“第三”,新行动(第三个案例)}
};
//在你的问题中,这是e.ColumnIndex
var ValueInColIndex=42;
//在您的问题中,这是dataGridView.Columns
var DataGridViewDatas=新字典
{
{“第一”,0},
{“第二”,42},
{“第三”,69}
};
foreach(MyDic中的var MyAction)
{
if(DataGridViewDatas[MyAction.Key]==ValueIncoldinEx)
{
MyAction.Value.DynamicInvoke();
}
}
}
产出:

第二种情况


我会有另一种方法,使用以这种方式构建的方法的
Dictionnary
(来自名称空间
System.Collections.Generic

键是datagridview中列的索引(“第一”、“第二”…)

该值是要执行的方法的委托(在每个if/else if中,什么将替换您的
//某些代码

例如:

/*
 * This example is written for console application, that can be tested easily.
 * The logic can be rewritten for WinForm
 */

static void TheFirstCase()
{
    //This should be replaced by the differents actions you want to do
    Console.WriteLine("first case"); 
}

static void TheSecondtCase()
{
    Console.WriteLine("second case");
}

static void TheThirdCase()
{
    Console.WriteLine("third case");
}

static void Main(string[] args)
{
    Dictionary<string, Delegate> MyDic = new Dictionary<string, Delegate>
    {
        //If you need parameters in the TheFirstCase(), use new Action<TypeOfTheFirstParam, TypeOfTheSecondParam, ...>(TheFirstCase)
        //If your Method needs to return something, use Func instead of Action
        { "First", new Action(TheFirstCase) }, 
        { "Second", new Action(TheSecondtCase) },
        { "Third", new Action(TheThirdCase) }
    };
    // in your question, this is e.ColumnIndex
    var ValueInColIndex = 42;

    // in your question, this is dataGridView.Columns
    var DataGridViewDatas = new Dictionary<string, int>
    {
        {  "First", 0 },
        {  "Second", 42 },
        {  "Third", 69 }
    };

    foreach (var MyAction in MyDic)
    {
        if (DataGridViewDatas[MyAction.Key] == ValueInColIndex)
        {
            MyAction.Value.DynamicInvoke();
        }
    }
}
/*
*这个例子是为控制台应用程序编写的,可以很容易地进行测试。
*可以为WinForm重写逻辑
*/
静态作废第一个案例()
{
//这应该被您想要执行的不同操作所取代
控制台写入线(“第一个案例”);
}
静态无效第二种情况()
{
Console.WriteLine(“第二种情况”);
}
静态无效第三种情况()
{
Console.WriteLine(“第三种情况”);
}
静态void Main(字符串[]参数)
{
字典MyDic=新字典
{
//如果在TheFirstCase()中需要参数,请使用新操作(TheFirstCase)
//如果您的方法需要返回某些内容,请使用Func而不是Action
{“第一”,新行动(第一种情况)},
{“第二”,新动作(第二幕)},
{“第三”,新行动(第三个案例)}
};
//在你的问题中,这是e.ColumnIndex
var ValueInColIndex=42;
//在您的问题中,这是dataGridView.Columns
var DataGridViewDatas=新字典
{
{“第一”,0},
{“第二”,42},
{“第三”,69}
};
foreach(MyDic中的var MyAction)
{
if(DataGridViewDatas[MyAction.Key]==ValueIncoldinEx)
{
MyAction.Value.DynamicInvoke();
}
}
}
产出:

第二种情况


如果无法使用C#7.0中的模式匹配,还有另一种方法,即使用口述记录,其中键是函数,检查条件(案例),值是要执行的操作。对于代码,它看起来像:

private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
    var caseDictionary = new Dictionary<Func<bool>, Action>()
    {
        { () => (e.ColumnIndex == dataGridView1.Columns["First"].Index), () => {  MessageBox.Show("First");}},
        { () => (e.ColumnIndex == dataGridView1.Columns["Second"].Index), () => { MessageBox.Show("Second");}},
        { () => (e.ColumnIndex == dataGridView1.Columns["Third"].Index), () => { MessageBox.Show("Third");}}
    };
    caseDictionary.Where(caseRecord => caseRecord.Key()).Select(action => action.Value).FirstOrDefault()?.Invoke();
}
private void dataGridView1\u CellValidating(对象发送方,DataGridViewCellValidatingEventArgs e)
{
var caseDictionary=newdictionary()
{
{()=>(e.ColumnIndex==dataGridView1.Columns[“First”].Index),()=>{MessageBox.Show(“First”);},
{()=>(e.ColumnIndex==dataGridView1.Columns[“Second”].Index),()=>{MessageBox.Show(“Second”);},
{()=>(e.ColumnIndex==dataGridView1.Columns[“Third”].Index),()=>{MessageBox.Show(“Third”);}
};
caseDictionary.Where(caseRecord=>caseRecord.Key()).Select(action=>action.Value.FirstOrDefault()?.Invoke();
}

当然,您可以在构造函数中声明字典,并在
CellValidating
事件中调用它。

如果无法使用C#7.0中的模式匹配,还有另一种方法,即使用dictonary,其中键是检查条件(cases)的函数这些值是您要执行的操作。对于您的代码,它将如下所示:

private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
    var caseDictionary = new Dictionary<Func<bool>, Action>()
    {
        { () => (e.ColumnIndex == dataGridView1.Columns["First"].Index), () => {  MessageBox.Show("First");}},
        { () => (e.ColumnIndex == dataGridView1.Columns["Second"].Index), () => { MessageBox.Show("Second");}},
        { () => (e.ColumnIndex == dataGridView1.Columns["Third"].Index), () => { MessageBox.Show("Third");}}
    };
    caseDictionary.Where(caseRecord => caseRecord.Key()).Select(action => action.Value).FirstOrDefault()?.Invoke();
}
private void dataGridView1\u CellValidating(对象发送方,DataGridViewCellValidatingEventArgs e)
{
var caseDictionary=newdictionary()
{
{()=>(e.ColumnIndex==dataGridView1.Columns[“First”].Index),()=>{MessageBox.Show(“First”);},
{()=>(e.ColumnIndex==dataGridView1.Columns[“Second”].Index),()=>{MessageBox.Show(“Second”);},
{()=>(e.ColumnIndex==dataGridView1.Columns[“Third”].Index),()=>{MessageBox.Show(“Third”);}
};
caseDictionary.Where(caseRecord=>caseRecord.Key()