简体   繁体   中英

C# extend indexer?

Is it possible to use extension methods to extend an indexer? I want to be able to get cell's value from DataGridViewCell of given DataGridViewRow using header text like this:

object o = row["HeaderText"]; 

I have this code

public static class Ext
{
    public static object Cells(this DataGridViewRow r, string header)
    {
        foreach (DataGridViewCell c in r.Cells)
        {
            if (c.OwningColumn.HeaderText == header)
            {
                return c.Value;
            }
        }
        return null;
    }
}

and I want similar indexer. Thanks.

Indexers are actually properties, and extension properties do not exist in C#. So this can't be done the way you want.

See this blog post for some background on the subject, and an explanation as to why that feature was considered, but ultimately omitted from C# 3.0.

No, it isn't. Extension methods are just syntactic sugar for static method call, an indexer is a property.

Doing

object o = new object();
o.ExtensionMethod();

is equivalent to

object o = new object();
Extensions.ExtensionMethod(o);

Extension methods don't change the class in any way, they just provide you with a simpler interface to call static methods.

Unfortunately, no. This would effectively be an "extension property", which isn't supported. You must have it as a method, like your current code.

Note that extension properties have been requested on Connect on multiple occasions , but have never been included in the language.

不,您不能使用扩展方法扩展运算符,例如索引器。

No this is not possible. Extension methods are limited to methods only. They can't provide properties, indexers or constructors

作为扩展属性的解决方法,您可以使用基于反射的对象索引器代码为对象实现 Getter 和 Setter 扩展方法。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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