Question

I'm using Mvc3 and NHibernate I have a class called Activation code like following:

public virtual int LoginAccountId { get; set; }
protected virtual string ActivatedCode { get; set; }
protected virtual DateTime ActivationDate { get; set; }

I want to access this field in a controller lik

ActivationCode code=new ActivationCode();
code.ActivatedCode="abc";

but not able to get it. why?

Était-ce utile?

La solution

The property is protected which means you can access it only from inside the class or inside one of it's inheritances.

public class ActivationCode{
    public virtual int LoginAccountId { get; set; }
    protected virtual string ActivatedCode { get; set; }
    protected virtual DateTime ActivationDate { get; set; }
    
    public void Foo(){
        var x = this.ActivatedCode; // Valid
    }

}

public class Foo{
    new ActivationCode().ActivatedCode //Invalid access
}

You can change the properties from protected to public just like with LoginAccountId.

Read MSDN article about protected:

The protected keyword is a member access modifier. A protected member is accessible from within the class in which it is declared, and from within any class derived from the class that declared this member.

A protected member of a base class is accessible in a derived class only if the access takes place through the derived class type. For example, consider the following code segment:

Update:

The ActivationCode class should look like this:

public class ActivationCode
{
    public virtual int LoginAccountId { get; set; }
    public virtual string ActivatedCode { get; set; }
    public virtual DateTime ActivationDate { get; set; }
}

Autres conseils

You cannot access protected members from outside of the class that contains them or from derived classes. If you don't change the visibility of the member the only way to access it from outside of the ActivationCode class is to use Reflection but that would be absolutely horrible. I would recommend making it public or exposing a public method that will allow you to modify its value.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top