开发者

Passing an interface to a base class - C#

开发者 https://www.devze.com 2023-01-31 12:37 出处:网络
If I have the following code: public abstract BaseClass { public void SendName(<Take in an interface>)

If I have the following code:

public abstract BaseClass
{
    public void SendName(<Take in an interface>)
    { // Do stuff }
}

public class Derived : BaseClass, IMyProperties
{
   public string IMy开发者_C百科Properties.Name { get; set; }

   public void Derived()
   {
       IProperties.Name = "Dave";
   }

   public void SendNameToBase
   {
     base.SendName(//I want to send IProperties);
   }
}

How do I send IProperties to the base class?


Your base class's method should be defined like such:

public void SendName(IProperties props) 
{ // Do stuff } 

You call this method from the child class like this: (assuming you want to pass the current instance of the your child class, since it implements IProperties)

base.SendName(this);

Note: I'm also assuming that IMyProperties == IProperties in your code example.


well since you explicitly setup the interface, you would have to do

base.SendName((IMyProperties)this);


What exactly do you mean by sending an interface?

If you want to pass the type statically, you can use a generic (i.e. templated) method:

public void SendName<T>(T properties)
    where T : IProperties    // types passed in must derive from IProperties
{
    var name = properties.Name;
    // ...
}

//...

// Usage:
base.SendName<IProperties>(this);

If you want to send the type at runtime, you can pass around Type objects:

public void SendName(Type type)
{ /* Do stuff */ }

//...

// Usage:
base.SendName(typeof(IProperties));


I am not sure what you are trying to accomplish, but maybe if you declared the variable in the base clase you would be able to access IProperties in both functions

public abstract BaseClass 
{
   public string IMyProperties.Name { get; set; }
   public void SendName(<Take in an interface>) 
   { // Do stuff } 
} 
0

精彩评论

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

关注公众号