开发者

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜