简体   繁体   English

如何使用具有扩展方法的索引器具有参数和函数调用

[英]How to use indexers with Extension Methods having out parameter and function calls

Is it possible to use indexers with extension methods. 是否可以使用带extension方法的indexers

eg. 例如。 Consider it as an example only. 仅将其视为一个示例。

    public static object SelectedValue(this DataGridView dgv, string ColumnName)
    {            
        return dgv.SelectedRows[0].Cells[ColumnName].Value;
    }

EDIT 编辑

  1. usage mygrid.SelectedValue("mycol") 用法mygrid.SelectedValue("mycol")

  2. How to use it as an indexer mygrid.SelectedValue["mycol"] rather than above one. 如何使用它作为索引器mygrid.SelectedValue["mycol"]而不是上面的一个。

  3. Is it possible to use it like this as well ? 是否可以像这样使用它? mygrid.SelectedValue["mycol"](out somevalue);

What are the syntax of getting this kind of values. 获得这种价值的语法是什么? Any simple example or link will work. 任何简单的示例或链接都可以。

Well, there are two issues here: 嗯,这里有两个问题:

  • C# doesn't (by and large) support named indexers 1 C#(基本上)不支持命名索引器1
  • C# doesn't support extension properties, so you can't make SelectedValue a property returning something indexable instead C#不支持扩展属性,因此您无法使SelectedValue成为返回可索引的属性

So no, the syntax you've specified there won't work. 所以不,你在那里指定的语法是行不通的。 You could get this to work: 可以让它工作:

mygrid.SelectedValue()["mycol"]

but that's a bit ugly. 但那有点难看。 I'd stick with the method form if I were you. 如果我是你,我会坚持使用方法表格。


1 C# 4 supports calling named indexers on COM objects. 1 C#4支持在COM对象上调用命名索引器。

Let me try to clarify the usage and intentions of Extension Method . 让我试着澄清Extension Method的用法和意图。

Consider a Extension Method 考虑Extension Method

public static bool IsNullOrEmpty(this string source)
{
    return source == null || source == string.Empty;
}

Now you extend your string class with this Extension Method 现在,使用此Extension Method扩展string

var myString = "Hello World";
Assert.AreEqual(myString.IsNullOrEmpty(), false);

This is what .NET does on compilation: 这就是.NET在编译时所做的事情:

public static bool IsNullOrEmpty(string source)
{
    return source == null || source == string.Empty;
}

Using our old school 用我们的旧学校

var myString = "Hello World";
Assert.AreEqual(IsNullOrEmpty(myString), false);

Extension method is nothing but a visualization to what we were used to do. 扩展方法只不过是我们过去所做的可视化。

Well, extending indexers could be possible but Microsoft did not think about it. 好吧,扩展索引器是可能的,但微软没有想到它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM