how to achieve calling a function dynamically, thats right the function to be called is decided from database values, using c#

ⅰ亾dé卋堺 提交于 2020-01-25 21:22:06

问题


the application is very large so giving a brief back ground and the problem

when the user logs in, a button is displayed having the text of the function he is allowed to call.

the function he is allowed is mapped in the database table

its made sure that the name of the actual function is same to the ones used in the db.

problem

the name is extracted, and stored as text field of button and also in a string variable.

now how am i supposed to call this function using the string variable which has the name stored in it!

like we type

name-of-function();

but here i dont know the name, the string at run time does so i cant write like

string()!!?


回答1:


You will need to use reflection to do this. Here is a rough sketch of what you need to do:

// Get the Type on which your method resides:
Type t = typeof(SomeType);
// Get the method
MethodInfo m = t.GetMethod("methodNameFromDb");
// Invoke dynamically
m.Invoke(instance, null);

Depending on your actual needs you will have to modify this a little - lookup the used methods and types on MSDN: MethodInfo, Invoke




回答2:


Well, no matter what you do, there is going to have to be some kind of mapping done between a database "function" and your "real" function. You can probably use Reflection using your Types and MethodInfo.

However, this sounds like a maintenance nightmare. It also sounds like you are reinventing user roles or the like. I would be very cautious about going down this path - I think it will be much more complex and problematic than you think.



来源:https://stackoverflow.com/questions/3918431/how-to-achieve-calling-a-function-dynamically-thats-right-the-function-to-be-ca

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!