C# 不可预见的字典行为

C# 不可预见的字典行为,c#,C#,在使用C#字典类时,我遇到了一些奇怪的行为。 首先介绍一下: 我对一个叫做AVariable的类有一个定义: public class AVariable { public AType VarType { get; set; } public AObject Value { get; set; } public AVariable(AObject val, AType type) { VarType = type; Value

在使用C#
字典
类时,我遇到了一些奇怪的行为。 首先介绍一下:

我对一个叫做AVariable的类有一个定义:

public class AVariable
{
    public AType VarType { get; set; }

    public AObject Value { get; set; }

    public AVariable(AObject val, AType type)
    {
        VarType = type;
        Value = val;
    }
}
下面的类在将这些变量插入字典时处理它们

public class VariablePool
{
    private readonly Dictionary<string, AVariable> _runtimeVariableMap;

    public VariablePool()
    {
        _runtimeVariableMap = new Dictionary<string, AVariable>();
    }

    public void AddNewVariable(string name, AVariable vrb)
    {
        _runtimeVariableMap[name] = vrb;
    }

    public void DebugDump(TextWriter tw) // Just a demo for here
    { ... prints out stuff about variable...  }
} 
编辑:A[类型]层次结构

public class AObject
{
}

public class AString : AObject
{
    private static string _rawStr;

    public AString(string str)
    {
        _rawStr = str;
    }

    public AString(AString str)
    {
        _rawStr = str.GetRawValue();
    }

    public string GetRawValue()
    {
        return _rawStr;
    }
}

public class ANumeric : AObject
{
    private static double _rawVal;

    public ANumeric(double val)
    {
        _rawVal = val;
    }

    public ANumeric(ANumeric num)
    {
        _rawVal = num.GetRawValue();
    }

    public double GetRawValue()
    {
        return _rawVal;
    }
}
我期望的是
DebugDump
的输出:

Name: a
Type: ANumeric
Value: 120

Name: b
Type: ANumeric
Value: 130


Name: c
Type: AString
Value: Hello

Name: d
Type: AString
Value: World
实际发生的情况:

Name: a
Type: ANumeric
Value: 130

Name: b
Type: ANumeric
Value: 130

Name: c
Type: AString
Value: World


Name: d
Type: AString
Value: World
我的问题很简单:为什么会这样?为什么最后一个
值应用于相同类型的所有变量

谢谢你抽出时间

编辑:
GetRawValue()返回在构造函数中分配的私有成员

在此处移除静电干扰:

private static string _rawStr
阅读,尤其是:

无论创建了多少个类实例,静态成员只存在一个副本


我想我从来没有见过有房地产支持的房地产。你可以说
public-AType-VarType{get;private set;}
@BradleyDotNET
dic[x]=y
是有效的-它只是添加或覆盖了我也看不到任何东西-你能发布
GetRawValue()
吗?如果没有
AType
AObject
,我们就无法重现这个问题,这是没有帮助的。请发布一个简短但完整的程序来演示这个问题。另外,只需使用自动实现的属性,而不是让一个属性调用另一个属性,就可以大大减少
可变的
代码。有什么是静态的吗?如果在ANumeric或AString构造函数中写入的字段是静态的,你会看到这种行为,因为你会从不同对象的构造函数中覆盖相同的静态字段。我现在感觉不太聪明。这就解决了问题。谢谢
private static string _rawStr