C #: Converting Get / Set from vb.net to C #

Can someone help.

I have vB.net and need to convert it to C #. At first it was pretty simple, 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 vb.net - pay attention to NamedObject

Public Property Datos(ByVal NamedObject As String) As T Get Return CType(HttpContext.Current.Session.Item(NamedObject ), T) End Get Set(ByVal Value As T) HttpContext.Current.Session.Item(NamedObject ) = Value End Set End Property 

and this is C #, but these are errors, since it appears, I can not pass the parameter in the property

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

I would be grateful for any input.

thanks

+4
source share
4 answers

You are looking for an indexer property. Basically implement a property called this . There is a good tutorial here .

True, you are limited to one index, but you can implement something like this:

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

C # does not support named parametric properties such as VB.NET. To do this, you need to create two methods:

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

To emulate the named indexed properties in C #, you need to create a proxy object as follows. However, I 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, just provide read-only:

 private readonly DatosProxy _datos = new DatosProxy(); public DatosProxy Datos { get { return _datos; } } 

Please note that this is not a 100% equivalent code, but usage is identical from the point of view of users.

+1
source

In C #, you can make an indexer, but an unnamed indexer:

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

You can create a collection that uses 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
source

Source: https://habr.com/ru/post/1303659/


All Articles