Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Converting Roslyn attributes to C# attributes #47

Open
Atlinx opened this issue Aug 30, 2022 · 0 comments
Open

Converting Roslyn attributes to C# attributes #47

Atlinx opened this issue Aug 30, 2022 · 0 comments

Comments

@Atlinx
Copy link

Atlinx commented Aug 30, 2022

I haven't found a way to get references working yet, so I've just copied the attributes file over to the code generator csproj. Here's the extension method I use to convert Rosyln source code attributes to instances of regular C# attributes.

        public static T MapToType<T>(this AttributeData attributeData) where T : Attribute
        {
            T attribute;
            if (attributeData.AttributeConstructor != null && attributeData.ConstructorArguments.Length > 0)
            {
                attribute = (T)Activator.CreateInstance(typeof(T), attributeData.GetActualConstuctorParams().ToArray());
            }
            else
            {
                attribute = (T)Activator.CreateInstance(typeof(T));
            }
            foreach (var p in attributeData.NamedArguments)
            {
                var field = typeof(T).GetField(p.Key);
                if (field != null)
                    field.SetValue(attribute, p.Value.Value);
                else
                    typeof(T).GetProperty(p.Key).SetValue(attribute, p.Value.Value);
            }
            return attribute;
        }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant