开发者

Visual Basic Default Property vs C# Property

I'm converting Visual Basic.Net code to C# in my project. But I have some doubts on how to convert Visual Basic default property to C#. The first option that comes to me are the indexers. Lets imagine the next code in Visual Basic

Public Class MyClass
Dim MyHash as Hashtable

Public sub New()
    MyHash = New Hashtable()
    MyHash.Add("e1",1)
    MyHash.Add("e2",2)
    MyHash.Add("e3",3)
End Sub

Defaul Propery MyDefProp(ByVal key as string) as Object
  Get
    Return MyHash(key)
  End Get

  Set(ByVal ObjectToStore As Object)
    MyHa开发者_StackOverflowsh(key) = ObjectToStore
  End Set
End Property

Converted this to C#:

public class MyClass
{
    private Hashtable MyHash;

    public MyClass()
    {
        MyHash = new Hashtable();
        MyHash.Add("A1",1);
        MyHash.Add("A2",2);
        MyHash.Add("A3",3);
    }

    public object this[string key]
    {
        get
        {
            return MyHash[key]; 
        }

        set
        {
            MyHash[key] = value;
        }
    }     
}

Am I correct on this?


You are correct.

The only difference is that the VB.Net version also creates a named indexed property; C# does not support named indexed properties.


While C# does support the default property syntax, your indexer will meet that need nicely.


As of 2022 you absolutely can index a class by name in C#. Just add this to your class definition:

public object this[string key]
{
   get { return this.GetType().GetProperty(key).GetValue(this, new object[0]); }
}

You can add a setter to this and your no longer stuck with just dot notation

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜