C# Compiler : cannot access static method in a non-static context

前端 未结 5 658
独厮守ぢ
独厮守ぢ 2020-12-18 17:48

I have the code below :

public class Anything
{
    public int Data { get; set;}
}

public class MyGenericBase
{
    public void InstanceMethod(T da         


        
5条回答
  •  生来不讨喜
    2020-12-18 18:31

    Since it is 9 years ago, I know it is way too many years ago. I go ahead and practiced C# without caring rl implementation. I think that your post has no goal in doing inheritance, OOAD, nor encapsulation (info hiding).

    From your code to my code here.

    public class Anything
    {
        private int data, data2; //field
    
        public Anything()
        {
            data = default(int);
        }
        public int Data { get; set; }
    }
    
    public class GenericParentClass
    {
        public static void StaticMethod(T data)
        {
            // do some job
        }
    
        public void InstanceMethod(T data)
        {
            // do some job
        }
    }
    
    public sealed class UsefulController : GenericParentClass where  T : Anything, new()
    {
        //all static public methods must be placed before all non-static public methods. [StyleCop Rule: SA1204]
        public static new void StaticMethod(T data)  //'UsefulController'.StaticMethod(Anything) hides inherited member 'GenericParentClass.StaticMethod(Anything)'. Use the new keyword if hiding was intended.
        {
            GenericParentClass.StaticMethod(data);  //'data' is a variable but used like a type //arugement type T is not assignable to parameter type 'data'.
        }
    
        public void EncapsulatedStaticMethod()
        {
            T @class = new T(); //cannot create an instance of the variable type T because it does not have the new() constraint. //T is type and @class is variable and new is an instance.
            StaticMethod(@class);  
        }
    
        public void EncapsulatedInstanceMethod(T data)
        {
            base.InstanceMethod(data);
        }
    }
    
    public class Container
    {
        public UsefulController  B { get; set; }
    }
    
    public class Testing   
    {
        public static void Main()
        {
            Anything @var = new Anything();
            var c = new Container();
            c.B.InstanceMethod(null);   
            c.B.EncapsulatedStaticMethod();    
            c.B.EncapsulatedInstanceMethod(var);  
        }
    }
    

提交回复
热议问题