开发者

C# Property inheritance question

开发者 https://www.devze.com 2022-12-30 04:09 出处:网络
How do i inherit a property in c# from an interface and give that property other name on the class? For example:

How do i inherit a property in c# from an interface and give that property other name on the class?

For example:

public interface IFoo
{
  int Num {get;set;}
}

public class IFooCls : IFoo
{
  int Ifoo.Num{get;set}
}

In this case, what the property name in the interface is also the same in the class. What i want is to give other property name on the class but still pointing to "N开发者_运维百科um" in the interface in this case. In VB, we can do it like this:

Public ReadOnly Property UserId() As String Implements System.Security.Principal.IIdentity.Name
    Get
        Return _userId
    End Get
End Property


Here is a way to simulate what you are trying to do in C#

public interface Foo {
  string Name {get;set;}
}

pubilc class Bar : Foo {

#region Foo implementation
  public string Name {get{return UserName;} set{UserName = value;}}
#endregion //Foo implementation

  public string UserName {get; set;}
}


If you inherit a property, you inherit it, name, type and all. There is no way to change the name.

If you want, you can write another property with a different name and call the inherited property from it (you still have to implement the original property).

See what you can do on this MSDN page.

The only way to achieve what you want (have a UserId property and impelement IIdentity) is to call IIdentity.Name from it).

This will hide the IIdentity.Name property from users of your class (unless they cast to IIdentity):

public class myIdentity : IIdentity
{
   public string IIdentity.Name {get; set;}

   public string UserId 
   { 
      get 
      { 
        return IIdentity.Name;
      }

      set 
      { 
        IIdentity.Name = value;
      }
}
0

精彩评论

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