简体   繁体   中英

Passing a Struct definition in C#

I have an issue with passing a struct definition to a function. Not an instance of a struct, but the definition.

We are open to alternative methods of doing what we want, but for right now, this is what we're trying to do -

We are writing a user control. This control is to display data in list form with headers, but what "list" it might be asked to display is unknown at design time. Right now we're taking the approach that, in order to keep things lightweight, we're going to pass to a Constructor and/or GetHeaders function a Struct definition. The headers would be pulled from the field names found in a passed structure definition, with data later coming in in both individual objects and lists of objects of that structure type.

Example. On the Control side:

    private void GetHeaders( dynamic _strc )
        {
        //Type _str_type = ((ObjectHandle) _str).Unwrap().GetType();
        FieldInfo[] fi = _strc.GetFields( BindingFlags.Public | BindingFlags.Instance );

        int _i = 0;

        foreach (FieldInfo _f in fi)
            {
            textBox1.Lines[_i] = _f.Name;
            }

        textBox1.Refresh();
        }

-Please note, I'm just trying to make sure I can parse the structure. We don't know if this will actually work yet since we can't get test to compile because of what is below.

The user will have their own struct definition to which the Control will not have direct access.

    public struct MineStruct
        {
        String ID;      // So we know who they are
        String Name;    // What we call them to their face
        String Nickname;// What we call them behind their back
        String Address; // We know where they live
        int Mileage;    // How far they've gone
        int Millage;    // How much they'll pay.  Oh, they'll pay...
        }

It will be passed at run-time, we had hoped, in something along these lines:

    private void button1_Click(object sender, EventArgs e)
        {
        GetHeaders( MineStruct );  //<-Error messaage here
        }

The error message we are getting is "'Form1.MineStruct' is a type. which is not valid in the given context" I've tried changing the GetHeaders function to take "Type", among other things, but nothing helps there.

So, my questions, in order are...

1) Is this a good way to approach the issue? We're completely open to doing another way, even passing a whole Class, but we'd like to keep it lightweight, which we believe this would be.

2) Is it even possible?

3) Is this actually lightweight?

4) If so, how do we pass a Struct Definition to a function in C#?

Maybe use a generic method instead of pass dynamic in parameter, to be sure than the parameter is a struct :

private void GetHeaders<T>(T str) where T : struct
{
     //Your code...
}    

What you're calling a "definition" is known as a Type in C#. If you know the name of the type you want information about (as is your case), you can use typeof(MineStruct) to get a Type object (which you mentioned you tried as the parameter of GetHeaders ), from which you can call GetFields to get its fields. If you had an object that you wanted to get type information about, you'd need to call myObj.GetType() instead.

As an aside, the struct's fields are private (the default situation in C#), so you'll need to use BindingFlags.NonPublic as in this answer .

Thank you all VERY MUCH! Putting together the various answers, we got it to work.

1) Changing the receiving parameter in GetHeaders to "Type" and using "typeof" in the calling function got the compiler on our side.

2) Adding the Binding Flag ".NonPublic" opened up the structure for viewing.

3) Using a Generic gave us a better approach to filling out the data once the control was established.

I I've sent upvotes to everyone, but I'm not as familiar with how StackOverflow operates as I'd like to be, so I hope you've all gotten the credit you deserve!我已经向每个人发送了赞成票,但我并不像我希望的那样熟悉 StackOverflow 的运作方式,所以我希望你们都得到了应有的荣誉! Thanks again!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM