C # properties as array notation

Using JavaScript, you can access an object using dot notation or array notation.

var myArray = {e1:"elem1",e2:"elem2",e3:"elem3",e4:"elem4"};
var val1 = myArray["e1"];
var val2 = myArray.e1;

Is it possible to accomplish this with C #?

This is what I tried:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(int id, FormCollection frmVals)
{
  string value;
  Owner owner = new Owner();

  foreach (var key in frmVals.AllKeys)
  {
    value = frmVals[key];
    owner[key] = value;  
  }
}
+3
source share
5 answers

While there is no way to do this with C #. You can change your code in several ways that can achieve your goal. First, you can use a dictionary like this:

var something = new Dictionary<string, object>() {
    { "property", "value"},
    { "property1", 1}
};
foreach (var keyVal in something) {
    var property = keyVal.Key;
    var propertyValue = keyVal.Value;
}

Another option is to do it dynamically:

dynamic somethingDyn = new System.Dynamic.ExpandoObject();
somethingDyn.property = "value";
somethingDyn.property1 = 1;

var somethingDynDict = (IDictionary<string, object>)somethingDyn;
var propValue = somethingDyn["property"];

foreach (var keyVal in somethingDynDict) {
    var property = keyVal.Key;
    var propertyValue = keyVal.Value;
}

If you need to iterate over properties on a strongly typed object, you can use reflection:

var owner = new Metis.Domain.User();
var properties = owner.GetType().GetProperties();
foreach (var prop in properties) {
    object value = prop.GetValue(owner, null);
}
+5
source

, , , , . - :

public object this[string key]
{
  get
  {
    var prop = typeof(ThisClassName).GetProperty(key);
    if (prop != null)
    {
      return prop.GetValue(this, null);
    }
    return null;
  }
  set
  {
    var prop = typeof(ThisClassName).GetProperty(key);
    if (prop != null)
    {
      prop.SetValue(this, value, null);
    }
  }
}
+3

Javascript -, #.

.

:

owner.key = frmVals[key];
owner.key2 = frmVals[key2];

- , , #.

+1

# , .

Dictionary, . - # , :

var myType = new { e1="elem1",e2="elem2",e3="elem3",e4="elem4"};
var val1 = myType.e1;

, , .

JavaScript, ExpandoObject, , - .

, , , , .

:

var myType = new MyType(new[]{
    {"e1", "elem1"},
    {"e2", "elem2"},
    {"e3", "elem3"},
    {"e4", "elem4"}});

, (, Tuple KeyValuePair). IEnumerable<T> .

+1

, .

:

1) .

  • , , System.Collections.Generic.Dictionary<string, blah>
  • Member access designation can be provided using DLR magic and keyword dynamic.

2) The list of keys and values โ€‹โ€‹is static.

  • Member access declaration already provided by C # compiler.
  • Array notation can be used using Reflection (hopefully with a cache to improve performance).

In the static case, member access notation is much faster. In the dynamic case, array notation will be slightly faster.

0
source

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


All Articles