c# - 如何获取旧式集合中项目的类型?

标签 c# generics type-constraints

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

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

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

使用

where T : IList<DataGridViewBand>

会很好,但由于 DataGridViewRowCollection(和 -Column-)只是从 IList 派生,所以这是行不通的。

在 C++ 中,我可能会使用特征习惯用法。有没有办法在 C# 中做到这一点,或者有更惯用的方法吗?

最佳答案

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

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

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

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

关于c# - 如何获取旧式集合中项目的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17280397/

相关文章:

c# - 使用 Get 将 ASP.Net MVC 中的 ViewModel 从一个 View 传递到另一个 View

c# - 使用 C# 安装 Msmq

带有循环元数据的 Swift 3.1 嵌套泛型错误

scala - 使用类型为编译时检查的任意约束建模

c# - 为什么不允许从 "class A : IX"到通用 "T where T : IX"的转换?

c# - 线程竞速,为什么线程这么工作?

c# - 如何将 IEnumerable<?> 转换为 IEnumerable<string>?

C# 从通用基类派生 (T : U<T>)

java - 带有 List<String> 的原始类型给出编译错误

scala - 如何定义一个参数类型不能为 Any 的 scala 方法