你真的想讓任何C#嗎?
如果是這樣,你可能想看看this script engine for C#。請記住,能夠運行任意代碼是一個巨大的安全風險。
如果您在等待.NET 4.0(現在測試版,今年晚些時候發佈)時可以使用,那麼您可以使用DLR或動態語言運行庫來實現此目的。另一方面,如果你不想依賴.NET 4.0,並且你願意限制自己,那麼你可以很簡單地使用Reflection。 如果你可以限制自己,例如,在DateTime實例上的方法,事情會更簡單。此示例顯示如何通過反射調用一個設置爲NOW的DateTime實例。
DateTime d = DateTime.Now;
string logicToInvoke= "Now.AddDays(12)";
string pattern = @"^Now\.(?<methodname>\w+)\((?<argstring>[^\)]*)\)";
RGX.Match match = RGX.Regex.Match(logicToInvoke, pattern);
// If match not found, logic is improperly formed.
if (!match.Success)
{
Console.WriteLine("The DateTime method logic is improperly formed.");
return;
}
// Store method and arg
string methodName = (string) match.Groups["methodname"].Value;
string argString = (string) match.Groups["argstring"].Value;
Console.WriteLine("Invoking method '{0}' with args '{1}'...", methodName, argString);
System.Type t= d.GetType();
try
{
switch (methodName)
{
case "AddDays" :
int daysToAdd = System.Int32.Parse(argString);
DateTime result = (DateTime) t.InvokeMember (methodName,
System.Reflection.BindingFlags.Public |
System.Reflection.BindingFlags.Instance |
System.Reflection.BindingFlags.InvokeMethod ,
null, d, new object [] {daysToAdd});
Console.WriteLine("Result: {0}", result.ToString("yyyy/MM/dd"));
break;
default:
Console.WriteLine("unsupported method: {0}", methodName);
break;
}
}
catch (System.Exception exc1)
{
Console.WriteLine("Exception while invoking method: {0}", exc1);
}
我建議保持DateTime值的格式與它的值分開。的時間(「YY/MM/DD」)的格式可能在屬性中更好的指定,與:
<Name>DateOne</Name>
<Value format="MM/dd/yy">[Now.AddDays(-1)]</Value>
你真的想允許任何C#代碼嗎?看起來像一個巨大的安全漏洞。 – Cheeso 2009-06-11 16:03:49