开发者

c#: Converting a Get / Set from vb.net to c#

Can anyone help.

I have the following in vb.net and need to convert it to c#. Seemed rather simple at first but I need to pass in the NamedObject variable as welll which is supported in vb.net but not in c#..

What are my options.

Here is the vb.net - notice the NamedObject

    Public Property Datos(ByVal NamedObject As String) As T
        Get
            Return CType(HttpContext.Current.Session.Item开发者_如何学Go(NamedObject ), T)
        End Get
        Set(ByVal Value As T)
            HttpContext.Current.Session.Item(NamedObject ) = Value
        End Set
    End Property

and this is c# but it errors as it appears i can't pass in a parameter on a property

    public T Datos(string NamedObject)
    {
        get { return (T)HttpContext.Current.Session[NamedObject]; }
        set { HttpContext.Current.Session[NamedObject] = Value; }
    }

I would appreciate any input..

Thanks


You are looking for the indexer property. Basically implement a property called this. There's a nice tutorial here.

True, you are restricted to the one indexer, but you will be able to implement something like this:

public T this[string namedObject]
{
    get { return (T)HttpContext.Current.Session[namedObject]; }
    set { HttpContext.Current.Session[namedObject] = Value; }
}


C# doesn't support named parameterful properties like VB.NET does. In order to make this work you will have to create two methods like this:

public T GetDatos(String NamedObject)
{
    return (T)HttpContext.Current.Session[NamedObject];
}
public void SetDatos(String NamedObject, T Value)
{
    HttpContext.Current.Session[NamedObject] = Value;
}


In order to emulate named indexed properties in C# you need to create a proxy object as follows. However, I would suggest a less direct translation if possible, for example as a function.

class DatosProxy<T> {
    public T this[string name] {
        get { return (T)HttpContext.Current.Session[name]; }
        set { HttpContext.Current.Session[name] = value; }
    }
}

And then, in your actual class, simply provide a read-only getter:

private readonly DatosProxy _datos = new DatosProxy();

public DatosProxy Datos { get { return _datos; } }

Notice that this is not 100% equivalent code but the usage from the user’s point of view is identical.


In C# you can make an indexer, but not a named indexer:

public T this[string name]
{
    get { return (T)HttpContext.Current.Session[name]; }
    set { HttpContext.Current.Session[name] = Value; }
}

You can make a collection that uses the Session state as storage, and declare a property that returns the collection:

public class DatosCollection {

  public T this[string name] {
    get { return (T)HttpContext.Current.Session[name]; }
    set { HttpContext.Current.Session[name] = value; }
  }

}

private _collection = new DatosCollection();

public DatosCollection Datos { get { return _collection; } }
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜