偶尔我喜欢花一些时间查看.NET代码,看看事情是如何在幕后实现的.我在String.Equals通过Reflector 查看方法时偶然发现了这个宝石.
C#
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
public override bool Equals(object obj)
{
string strB = obj as string;
if ((strB == null) && (this != null))
{
return false;
}
return EqualsHelper(this, strB);
}
Run Code Online (Sandbox Code Playgroud)
IL
.method public hidebysig virtual instance bool Equals(object obj) cil managed
{
.custom instance void System.Runtime.ConstrainedExecution.ReliabilityContractAttribute::.ctor(valuetype System.Runtime.ConstrainedExecution.Consistency, valuetype System.Runtime.ConstrainedExecution.Cer) = { int32(3) int32(1) }
.maxstack 2
.locals init (
[0] string str)
L_0000: ldarg.1
L_0001: isinst string
L_0006: stloc.0
L_0007: ldloc.0
L_0008: brtrue.s L_000f
L_000a: …Run Code Online (Sandbox Code Playgroud) 是否有可能在不创建实例的情况下获得价值?
我有这门课:
public class MyClass
{
public string Name{ get{ return "David"; } }
public MyClass()
{
}
}
Run Code Online (Sandbox Code Playgroud)
现在我需要获取值"David",而不创建MyClass的实例.
我有一种情况,很少有对象的队列出列空.对Enqueue的唯一调用是在类本身内:
m_DeltaQueue.Enqueue(this);
Run Code Online (Sandbox Code Playgroud)
很少,null在以下代码中从此队列中出列(静态方法):
while (m_DeltaQueue.Count > 0 && index++ < count)
if ((m = m_DeltaQueue.Dequeue()) != null)
m.ProcessDelta();
else if (nullcount++ < 10)
{
Core.InvokeBroadcastEvent(AccessLevel.GameMaster, "A Rougue null exception was caught, m_DeltaQueue.Dequeue of a null occurred. Please inform an developer.");
Console.WriteLine("m_DeltaQueue.Dequeue of a null occurred: m_DeltaQueue is not null. m_DeltaQueue.count:{0}", m_DeltaQueue.Count);
}
Run Code Online (Sandbox Code Playgroud)
这是生成的错误报告:
[Jan 23 01:53:13]:m_DeltaQueue.发生null的取消:m_DeltaQueue不为null.m_DeltaQueue.count:345
关于如何在此队列中出现空值,我感到非常困惑.
在我写这篇文章时,我想知道这是否可能是线程同步的失败; 这是一个多线程应用程序,可能在另一个线程中同时发生入队或出队.
目前这是在.Net 4.0下,但它以前发生在3.5/2.0
更新:
这是我(希望是正确的)解决问题的方法,尽管下面的重要答案是同步问题,但这个解决方案已经明确了.
private static object _lock = new object();
private static Queue<Mobile> m_DeltaQueue = new Queue<Mobile>();
Run Code Online (Sandbox Code Playgroud)
排队:
lock (_lock) …Run Code Online (Sandbox Code Playgroud) 我注意到Delegate类有一个Target属性,(可能)返回委托方法将执行的实例.我想做这样的事情:
void PossiblyExecuteDelegate(Action<int> method)
{
if (method.Target == null)
{
// delegate instance target is null
// do something
}
else
{
method(10);
// do something else
}
}
Run Code Online (Sandbox Code Playgroud)
在调用它时,我想做类似的事情:
class A
{
void Method(int a) {}
static void Main(string[] args)
{
A a = null;
Action<int> action = a.Method;
PossiblyExecuteDelegate(action);
}
}
Run Code Online (Sandbox Code Playgroud)
但是当我尝试构造委托时,我得到一个ArgumentException(委托给一个实例方法不能有一个null'this').我想做的是什么,我该怎么做?