简体   繁体   中英

Read referenced namespaces from Type

I need a way to check out all namespaces used by a type via reflection.

namespace My.Program.BaseTypes
{
    using System;
    using System.Text;
    using My.Program.Extenders;
    using My.Program.Helpers;
    using My.Program.Interfaces;

    public class MyTypeBase
    {
        public MyTypeBase()
        {
        }

        public My.Program.Helpers.HelperTypeX X
        {
            get;
            set;
        }

        public My.Program.Extenders.ExtenderTypeY Y
        {
            get;
            set;
        }

        public My.Program.Interfaces.InterfaceZ IZ
        {
            get;
            set;
        }
    }
}

I have only the Type of MyTypeBase in my code and need to find out with reflection all referenced namespaces of all Properties in MyTypeBase.

Sure I could loop through all Properties, get the types from them and check their namespaces, but is there a cleaner way of achiving this goal?

To prevent the question, it is for writing a generator which shall create new classes based on some legacy code.

No, I can't think of a cleaner way of doing this. There's no real concept of the type itself using a bunch of namespaces - it has members which themselves refer to types (either in property/return type, field type, event handler type, the type of a nested class, or a parameter type) but those are just individual members.

On the plus side, with LINQ it shouldn't be hard to do... something like:

var namespaces = type.GetProperties()
                     .Select(p => p.PropertyType.Namespace)
                     .Distinct();

Note that that won't pick up the namespaces of indexer parameter types.

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