开发者

Change from const to property and static context (C#)

I had a public class like that:

public class ClassN
{
    public const int Som开发者_如何学运维eInt = 16;
    ...
}

This was called from somewhere else using

int myInt = ClassN.SomeInt

Now I have to change the 16 to something more dynamic and that looks like this:

public int SomeInt
{
    get
    {
         //this method is not static and cant be changed to static 
         return GetIntDynamically();    
    }
}

Of course the call is not working anymore, because of static context. I cant create a new instance of ClassN ... what another option that does not violate coding rules?

Thanks


If GetIntDynamically is not static and can't be made static, you have no other option as to create an instance of ClassN.


If you can't create a new instance of ClassN, but your method is relying on some instance state by using the this keyword, then you are needing to call the method on a particular known instance of ClassN. If it's the only such, then you could perhaps consider implementing a singleton pattern. If it's not the only such instance, then you will need to make a reference to the right instance available to your calling code. So as I said in my comment, we need to understand more about your situation to answer this fully. However, the singleton pattern may be what you are after...


Is this what you are looking for?

public class ClassN 
{
    public static int SomeInt = 16;     
    ...
} 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜