是否可以在同一个类中引用一个类?怎么样?

时间:2014-11-19 14:42:17

标签: c# class oop

是否可以在同一个类中引用一个类...我的意思是在下面的代码中,我必须从保存的文件中获取属性值,这是我想要返回的内容。

public class MyClass
{
    private string attr1 = "atrribute 1";   
    public string Attr1
    {
        get
        {
            //In the line below, I have to reference the type of the class "MyClass"

            if (MyFileStorage.ReadSharedData<MyClass>("filename.xml").prop1.Equals(String.Empty))
               return attr1;
            else
               return MyFileStorage.ReadSharedData<MyClass>("filename.xml").prop1;
        }
        set
        {
            MyFileStorage.WriteSharedData("filename.xml", value);
        }
    }

    private string attr2 = "atrribute 2";
    public string Attr2
    {
        get
        {
            return attr2
        }
        set
        {
            attr2 = value;
        }
    }
}

USAGE

public static MyClass myClass;
Debug.WriteLine(myClass.Attr1); //output: attribute 1
myClass.Attr1 = "xyz";
Debug.WriteLine(myClass.Attr1); //output: xyz (should be able to read this value from the Storage file)

然而,存在未知错误。这是不可能的,应用程序卡住了!

有人能告诉我如何从存储文件(已实现MUTEX)中读取属性值,并且它是两个项目中的共享文件并返回。

ReadSharedData实现:stackoverflow.com/questions/21596564 /

1 个答案:

答案 0 :(得分:0)

是的,它在身体上是可能的 - 尽管我不建议您尝试做什么 要使attr1为静态,以便它们共享相同的变量:

private static string attr1 = "atrribute 1";
或者总是返回文件,无论是否设置了private static string attr1 = "atrribute 1";
attr1
请记住,以上都不是好的做法。