开发者

How to Get Function String Assigned to Delegate

As you may know, when we have this code in Javascript :

function getName()
{
  var getName = "Hello";
  return getName;
}

var NameString = getName;

alert(NameString.toString());

will return ;

function getName()
{
  var getName = "Hello";
  return getName;
}

as string rather than the result of the function invocation.

How can I do the same thing in C# ?

For example how to get the function codes assigned to a Delegate ?

Thanks in advance.

(P.s : I think i开发者_高级运维t seems I may need to use System.Reflection)

The inner me thinks something like this :

public string delegate PointThat();

public string TheMethod()
{
  string getName = "Hello World";
  return getName;
}

// some function signature
{
  PointThat t = TheMethod;
  t.ToString() // returns the function string rather than invocation result   
}


Javascript is interpreted, C# is compiled. In interpreted languages you deploy the source while you deploy the compiled binary for compiled languages. There is no source anymore. You could parse the method via reflection and rebuild the source, but that is not the same.

Edit:

If you compile your C# files you get an exe or dll or whatever. That is binary executable code and no source code. Javascript on the other hand is always just text, the source code. If you embed JS into a webpage, the code can still be read. Try reading an exe or a dll with a text editor. You can't do that. Its binary, the source code is gone. Thats why you cannot print out the source of your method.

http://en.wikipedia.org/wiki/Interpreter_%28computing%29
http://en.wikipedia.org/wiki/Compiler

Also a delegate is basically a (typesafe) function pointer. That means it points to the function and does not contain it.

If you really want to understand the problem you need to understand the difference between a compiler and an interpreter (see the two links above).


In short, you can't (really).

That's because what you're seeing in javascript is actually an object, not just a function, while the C# code yields a (compiled) function which can be called.

Some of the options you have:

  • Get the function's metadata via reflection; this does not expose any of the functionality which is inside the function.

  • Go a step further and decompile the function (like Reflector does), still this doesn't yield the original source but a repro of it which should do the same thing.

  • Keep the source and compile it "on demand", but that requires also quite some interaction on your part.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜