开发者

Dynamic Method Creation

So, I have been trying to research this all morning, and have had no luck. I am trying to find a way to dynamically create a method/delegate/lambda that returns a new instance of a certain class (not known until runtime) that inherits from a certain base class.

I can guarantee the following about the unknown/dynamic class

  1. It will always inherit from one known Class (Row)
  2. It will have 开发者_如何转开发atleast 2 constructors (one accepting a long, and one accepting an IDataRecord)

I plan on doign the following:

  1. Finding all classes that have a certain attribute on them
  2. Creating a delegate/method/lambda/whatever that creates a new instance of the class
  3. Storing the delegate/whatever along with some properties in a struct/class
  4. Insert the struct into a hashtable
  5. When needed, pull the info out of the hashtable and calling the delegate/whatever to get a new instance of the class and returning it/adding it to a list/etc.

I need help only with #2 above!!! I have no idea where to start. I really just need some reference material to get me started, or some keywords to throw into google.

This is for a compact/simple to use ORM for our office here. I understand the above is not simple, but once working, should make maintaining the code incredibly simple.

Please let me know if you need any more info! And thanks in advance! :)


You can use LINQ expressions to construct the lambda (long p) => new XXX(p) as Row at runtime:

Type type = // ...
ConstructorInfo ctor = type.GetConstructor(new Type[] { typeof(long) });

var p = Expression.Parameter(typeof(long), "p");
var expr = Expression.Lambda<Func<long, Row>>(
               Expression.TypeAs(
                   Expression.New(ctor, p),
                   typeof(Row)),
               p);

Func<long, Row> rowCreator = expr.Compile();

Row row = rowCreator(10);


what about Activator.CreateInstance ?

sample:

string typeName = ...;
Activator.CreateInstance(Type.GetType(typeName), params);
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜