解决方案 »
- 多个客户端同时发送请求同一个webservic执行 增删改数据库。
- 如何获取与当前时间点相差20年的时间
- 请大家讨论下现在基于.net平台下的报表
- AxWebBrowser怎样用代理访问?
- 在线等___mssql数据库,有一个表的字段让我不小心update,想恢复
- 不用visual studio,如何引用我用tlbimp生成的托管的excel的dll文件?
- 如何将一个二维数组存入到一个一维数组中
- C#界面
- 大家来讨论一下C# 和Java ,回贴均有分!!
- [求助] winform中如何重写MessageBox?
- 水晶报表安装不上去
- 求助:计算当前日期是开学第几周(学校开学日期9月1日)C#实现
->
re_temp = new Regex(str_temp, RegexOptions.IgnoreCase);re_temp是不需要重新定义了,但是每次还得new的,因为你的str_temp变了
没有办法吗?我就是希望不重新new,然后修改正则表达式里的内容啊。。
replace函数行不行?如果行,应该怎么样?
你的代码里美用到
代码是经删减提取的。
我主要目的是,不希望每次都new,因为new会增加了内存的消耗啊。
是的,我是需要新的字符串来生成新的正则表达式。
但是又不想new,而是只是想修改原来的那个。
string str_temp="(new|old)";
Regex re_temp=null;
for(int i=0;i<10000;i++)
{
str_temp=refresh_str(str_temp); //refresh_str()是一个更新str_temp内容的函数。此函数每次执行后,str_temp的内容都会改变。
re_temp = new Regex(str_temp, RegexOptions.IgnoreCase);
}这样么? 不太明白什么意思
修改值类型的值,不需要new的,例子int i=3;i=6;
原来的代码进一步可以这样表示:string str_temp="(new|old)";
string str="I am a new man."
for(int i=0;i<10000;i++)
{
str_temp=refresh_str(str_temp); //refresh_str()是一个更新str_temp内容的函数。此函数每次执行后,str_temp的内容都会改变。
Regex re_temp = new Regex(str_temp, RegexOptions.IgnoreCase);
if(re_temp.Math(str))
{
this.textBlock.text+=str_temp+" \n";
}
}
这样在for得里面,还是new了啊,
new了就要重新分配一块新的内存
我明白你的意思。
那么,有没有好的方法,在一次循环结束的时候,释放Regex实例的内存块?
所以你代码里面,看似每个foreach循环都创建了一个Regex,其实编译器处理的时候,只会创建一个Regex,每次foreach里面的Regex都是在操作同一个对象。
static void Main(string[] args)
{
for (int i = 0; i < 10; i++)
{
int x = 2;
}
}以上代码 编译以后 结果为.method private hidebysig static void Main(string[] args) cil managed
{
.entrypoint
// 代码大小 23 (0x17)
.maxstack 2
.locals init ([0] int32 i,
[1] int32 x,
[2] bool CS$4$0000)
IL_0000: nop
IL_0001: ldc.i4.0
IL_0002: stloc.0
IL_0003: br.s IL_000d
IL_0005: nop
IL_0006: ldc.i4.2
IL_0007: stloc.1
IL_0008: nop
IL_0009: ldloc.0
IL_000a: ldc.i4.1
IL_000b: add
IL_000c: stloc.0
IL_000d: ldloc.0
IL_000e: ldc.i4.s 10
IL_0010: clt
IL_0012: stloc.2
IL_0013: ldloc.2
IL_0014: brtrue.s IL_0005
IL_0016: ret
} // end of method Program::Main
可以看出,编译器其实一共只创建了3个变量
.locals init ([0] int32 i,
[1] int32 x,
[2] bool CS$4$0000)
也就是i,x,和for循环中,用来判断的i < 10
同时
.maxstack 2
也说明了,栈深一共就2,只含有3个变量
所以根本不用担心for或者foreach循环里面,每次循环都会申请空间创建对象,for和foreach里面的声明,只会创建1次
static void Main(string[] args)
{
for (int i = 0; i < 10; i++)
{
Regex re = new Regex("dff");
}
}这个是针对你的正则表达式的结果.method private hidebysig static void Main(string[] args) cil managed
{
.entrypoint
// 代码大小 32 (0x20)
.maxstack 2
.locals init ([0] int32 i,
[1] class [System]System.Text.RegularExpressions.Regex re,
[2] bool CS$4$0000)
IL_0000: nop
IL_0001: ldc.i4.0
IL_0002: stloc.0
IL_0003: br.s IL_0016
IL_0005: nop
IL_0006: ldstr "dff"
IL_000b: newobj instance void [System]System.Text.RegularExpressions.Regex::.ctor(string)
IL_0010: stloc.1
IL_0011: nop
IL_0012: ldloc.0
IL_0013: ldc.i4.1
IL_0014: add
IL_0015: stloc.0
IL_0016: ldloc.0
IL_0017: ldc.i4.s 10
IL_0019: clt
IL_001b: stloc.2
IL_001c: ldloc.2
IL_001d: brtrue.s IL_0005
IL_001f: ret
} // end of method Program::Main
可见,结果也是一样的