如何获取旧样式集合中的项目类型?

Sar*_*ien 2 c# generics type-constraints

我实际上要做的是编写一个函数,允许我更改DataGridView中的选择,我想编写一个函数并将其用于行和列.这是一个简单的示例,取消选择所有内容并选择新的行或列:

private void SelectNew<T>(T collection, int index) where T : IList
{
  ClearSelection();
  collection[index].Selected = true;
}
Run Code Online (Sandbox Code Playgroud)

我的问题是,这不起作用,因为它无法派生,.Selected()因为这是非通用的IList.

运用

where T : IList<DataGridViewBand>
Run Code Online (Sandbox Code Playgroud)

会很好但是因为DataGridViewRowCollection(和-Column-)只是从IList派生而来,所以不起作用.

在C++中,我可能会使用traits idiom.有没有办法在C#中做到这一点,还是有更惯用的方式?

Ser*_*rvy 5

虽然理论上可以使用反射来做到这一点; 因为你的显式目标只是处理行或列,最简单的选择是为函数创建两个重载:

private void SelectNew(DataGridViewColumnCollection collection, int index)
{
    ClearSelection();
    collection[index].Selected = true;
}

private void SelectNew(DataGridViewRowCollection collection, int index)
{
    ClearSelection();
    collection[index].Selected = true;
}
Run Code Online (Sandbox Code Playgroud)

如果您尝试使用反射来执行此操作,它将起作用,但它会更慢,更不可读,并且存在无编译时保护的危险; 人们可以传入其他类型的没有Selected属性的列表,它会编译并在运行时失败.