C#可以这样做吗?利用变量存储一个判断条件。例如:

优途科技 2007-06-28 05:26:32
例如:

string temp;
string str;
if(a)
{
temp = "str == woaaa";
}
eles if(b)
{
temp = "str == wobbb";
}

if(temp的值)
{

}

这样肯定不行,但是如何能够实现这样的功能呢?就是为了少些几行代码!
...全文
201 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
Ivony 2007-06-28
  • 打赏
  • 举报
回复
Lambda表达式可以
bboyhbomb 2007-06-28
  • 打赏
  • 举报
回复
bool temp;
string str;
if(a)
{
temp = (str == woaaa) ? true : false;
}
if(b)
{
temp = (str == wobbb) ? true : false;
}

if(temp)
{

}

这样就可以,if的判断条件只能是true和false
roapzone 2007-06-28
  • 打赏
  • 举报
回复
其实你说的就是动态执行代码的问题:
参考:
http://www.cnblogs.com/tsoukw/archive/2005/06/01/165693.aspx
http://blog.csdn.net/wingfay/archive/2007/06/08/1643611.aspx
YUAN168 2007-06-28
  • 打赏
  • 举报
回复
比较复杂一点;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.CodeDom.Compiler;
using System.Reflection;
using Microsoft.CSharp;


namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
string str = "MessageBox.Show(\"无法找到参数!\");";
method_test(str);

}


private void method_test(string ACode)
{
ICodeCompiler vCodeCompiler = new CSharpCodeProvider().CreateCompiler();
CompilerParameters vCompilerParameters = new CompilerParameters();
vCompilerParameters.GenerateExecutable = false;
vCompilerParameters.GenerateInMemory = true;
vCompilerParameters.ReferencedAssemblies.Add("System.Windows.Forms.dll");
string vSource =
"using System.Windows.Forms;\n" +
"public class Temp\n" +
"{\n" +
" public void Test()\n" +
" {\n" +
" " + ACode + "\n" +
" }\n" +
"}\n";
CompilerResults vCompilerResults =
vCodeCompiler.CompileAssemblyFromSource(vCompilerParameters, vSource);

Assembly vAssembly = vCompilerResults.CompiledAssembly;
object vTemp = vAssembly.CreateInstance("Temp");
MethodInfo vTest = vTemp.GetType().GetMethod("Test");
vTest.Invoke(vTemp, null);
}

}
}=======================请参考上面的代码

Execute_Method方法中有一串字符,内容大
greatqn 2007-06-28
  • 打赏
  • 举报
回复
想简单是做不到。

想复杂的话这是动态代码执行,代码会更多。
优途科技 2007-06-28
  • 打赏
  • 举报
回复
temp其实存储的是一个表达式。

110,533

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧