开发者

Changing Variable Type on RunTime

开发者 https://www.devze.com 2023-04-03 04:22 出处:网络
Today i had a challenge with my College and i gaved up ,no idea how to achieve it . Is there a way to declare a String ,as Constant and on Load Event maybe using Reflection to change String to non-Con

Today i had a challenge with my College and i gaved up ,no idea how to achieve it . Is there a way to declare a String ,as Constant and on Load Event maybe using Reflection to change String to non-Constant assign a value from XML ,than Change it to Constant again .

And all of the Code which does that (Constant to Non-Constant),should be Stored in a String ,and on Load before Type Change ,it should be Decrypted and Injected into the Application .

example:

private const String RegNumber = "";
//Change RegNumber to Writable String
//Change RegNumber value
//Than Change RegNumber back to const again

PS : Please sorry but i 开发者_如何学JAVAhave no idea where to start ,and show here some code .


You can't declare it as const but you can declare it as static readonly:

private static readonly string Foo = ReadValueFromAssembly();

static string ReadValueFromAssembly()
{
    // Perform your logic and return the string here
}

Would that do everything you need? It's not really clear what you mean about the "code which does that [...] should be decrypted and injected into the application" but you can make the above method do anything you need it to as normal.

As a side-note, it's generally a bad idea to do a lot of work in a type initializer like this.

EDIT: You can store code as a string, use CSharpCodeProvider to compile it at execution time, and then execute the compiled code. I have a sample of this in "Snippy" which I used for C# in Depth as a quick tool for compiling snippets.


It may not even exist at runtime, the compiler could have just replaced all usages of it with their literal values (in fact, it probably has, though I don't think it's required to by the standard).

So no, I don't see how this could be possible.


It is theoratically possible. See

How to programmatically compile code using C# compiler

http://support.microsoft.com/kb/304655

You can write the code in a string and compile using the API mentioned in above article.

I have not done that before but it should give you an idea on how to start.

Also see,

Can I change value of constant in C#?

0

精彩评论

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

关注公众号