What is reflection in C#? Where do we use this 开发者_Go百科concept in our applications?
Reflection provides objects (of type Type) that encapsulate assemblies, modules and types. You can use reflection to dynamically create an instance of a type, bind the type to an existing object, or get the type from an existing object and invoke its methods or access its fields and properties. If you are using attributes in your code, reflection enables you to access them...
For reference, MSDN article on reflection and The Code Project has reflection pretty well explained..
For example, have a look at C# Reflection Examples.
From the documentation:
Reflection provides objects (of type Type) that encapsulate assemblies, modules and types. You can use reflection to dynamically create an instance of a type, bind the type to an existing object, or get the type from an existing object and invoke its methods or access its fields and properties. If you are using attributes in your code, Reflection enables you to access them. For more information, see Attributes.
Wikipedia says this:
In computer science, reflection is the process by which a computer program can observe and modify its own structure and behavior. The programming paradigm driven by reflection is called reflective programming. It is a particular kind of metaprogramming.
For example, if you want to programmatically display all the methods of a class, you could do it like so:
using System;
using System.Reflection;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var t = typeof(MyClass);
foreach (var m in t.GetMethods())
{
Console.WriteLine(m.Name);
}
Console.ReadLine();
}
}
public class MyClass
{
public int Add(int x, int y)
{
return x + y;
}
public int Subtract(int x, int y)
{
return x - y;
}
}
}
One use of reflection you will find in frameworks: to perform a particular function (in that framework) some class is used. But the exact class isn't known at compile time, instead it is configured in some text file, as the classname (usually including it's assembly). Using reflection you can take this string and create an instance of that particular class.
You have answers above of what reflection is, some cases where I've used it in the past:
- A generic method that takes in a list of properties and copies those properties in one object to another
- A method that uses the Description attribute to get text for enum, similar to this
Also see this article for examples of reflection, further links at bottom of the page.
精彩评论