Ari*_*ian 2 c# extension-methods thread-safety c#-4.0 c#-6.0
请考虑以下代码:
public static int ToInt (this string str)
{
return Convert.ToInt32 (str);
}
Run Code Online (Sandbox Code Playgroud)
我应该使用lock这个声明吗?
编辑1)
public static int ToInt(this string str)
{
int Id = -1;
if (str.IsEmpty() == true ||
int.TryParse(str.Trim().Replace(",", ""), out Id) == false)
{
throw new Exception("Invalid Parameter: " + str);
}
else
{
return Id;
}
}
Run Code Online (Sandbox Code Playgroud)
这个方法也是线程吗?
不,没有锁.
string是不可改变的; 因此,当您尝试解析它时,另一个线程无法更改其内容.
它与扩展方法没有任何关系; 根据他们做什么(或他们采取什么参数),那些可能是也可能不是线程安全的.
除了; 除非lock在守则的其他地方受到尊重; 这样做不会改变任何东西......(至少对于这种方法而言)