\"System.Console.WriteLine\"" />
开发者

C# - Get namespace function belongs to?

开发者 https://www.devze.com 2023-01-20 23:40 出处:网络
Something alike, if I input the string \"Console.WriteLine\", it would return -> \"System.Console.WriteLine\"

Something alike, if I input the string "Console.WriteLine", it would return -> "System.Console.WriteLine"

I assume the开发者_如何学Pythonre's some way via Reflection.


Well, the problem is slightly harder than you think.

First of all, it's pretty simple to scan all types in all loaded assemblies. So for instance, to find exactly what you're looking for, here's what you can do:

void Main()
{
    String input = "Console.WriteLine";

    var fullNames =
        (from asm in AppDomain.CurrentDomain.GetAssemblies()
         from type in asm.GetTypes()
         from member in type.GetMembers()
         let memberWithName = type.Name + "." + member.Name
         where memberWithName == input
         select type.FullName + "." + member.Name).Distinct();
     fullNames.Dump();
}

Note, the above code is written to run through LINQPad, the LINQ-query there is what you're looking for.

However, there's a slight problem.

What if the assembly isn't loaded (yet)? You won't find that then. Also, in the above query, the purpose behind the call to Distinct is that Console has a number of overloads. Granted, for your purpose, those would all produce the same name, hence the call to Distinct.

Also, note that if I create my own class called Console with a WriteLine method, the above code would find that as well, there's no way to distinguish between the two.

When you have such scenarios in your code (ie. multiple classes), the using directives at the top of the file dictates which one that will be found. With this code, there's no such thing, so you'd need to code in any rules for that yourself.

Now, a better question (from me to you) is what you intend to use this code for. Perhaps there's a better way to help you if you tell us what the ultimate purpose is.


Google the name; you will usually find the MSDN documentation, which gives you the namespace.

Using reflection, you would need to loop through every class in every namespace in every assembly looking for matches.

0

精彩评论

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