How to access members of an struct like an array in C#?

前端 未结 5 1110
余生分开走
余生分开走 2021-01-26 16:16

Lets say I have a struct with more than hundred elements with complex names. And I am passing a struct of the struct type described to a function using ref, like this:



        
5条回答
  •  生来不讨喜
    2021-01-26 16:52

    It's a strange request as you're expecting the order of the fields to be significant, but I suspect you could do this through Reflection or the TypeDescriptor.

    I would revise my code sample below to use proper property names with constants, but if you know the property names, just call the properties directly and save yourself from the reflection overhead. Otherwise, use a dictionary with constants.

    /* yeah, probably not a good idea.
    public void Foo(ref MyStruct a)
    {
        TypeDescriptor.GetProperties(a)[0].SetValue(a, 10);
    }
    */
    

提交回复
热议问题