2017-05-31 223 views
0

我有2个类,Child类继承Parent类。方法调用继承类

public class Parent 
{ 
    public string item{get;set;} 
} 

public class Child : Parent 
{ 
} 

public static void ConsoleWrite(Parent pitem) 
{ 
    Console.Write(pitem.item); 
} 

public static void Main() 
{ 
    ConsoleWrite(new Child(){item = "foo"}); 
} 

https://dotnetfiddle.net/yPriNl

ConsoleWrite方法应该只能用Parent对象调用,但它也可以用一个Child对象调用。有没有办法来阻止呢?

+3

为什么继承,如果你想阻止它?孩子具有父母的所有功能,所以它也可以在控制台上书写 –

+0

是的,可能的是,您只需要将继承从父母移除到孩子。这可能不是你想要的,在这种情况下,不,这是不可能的。这是OOP的基本规则。你已经说过,每个孩子也是父母,因此他们可以在父母预期的任何地方使用。 –

+0

@TimSchmelter我想阻止它只为一个方法,这是只为“父”对象,并没有意义的调用与继承对象 – Toshi

回答

1

一般是没有多大意义的,为什么你使用继承的全部,如果你不希望这样孩子们可以用于期望父母的方法吗?

你可以防止它在运行时抛出一个异常:

public static void ConsoleWrite(Parent pitem) 
{ 
    if(pitem?.GetType().IsSubclassOf(typeof(Parent)) == true) 
    { 
     throw new ArgumentException("Only parent type is allowed", nameof(pitem)); 
    } 

    Console.Write(pitem?.item); 
} 

也许你不想继承,但是,这两个类具有共同的特性,可以让他们实现相同的接口:

public interface IItem 
{ 
    string Item { get; set; } 
} 

public class Type1: IItem 
{ 
    public string Item { get; set; } 
} 

public class Type2 : IItem 
{ 
    public string Item { get; set; } 
} 

现在,他们不是父子所以不能用Type2实例中使用的是预计Type1的方法。但如果方法接受IItem您将有同样的问题;-)

1

我会建议组织你的父母在不同的命名空间,然后你的程序类的儿童类。将子类定义为私有。这种方式有将儿童elemnts用不上,但只有当它们被铸造家长:

namespace ClassesDemo 
{ 
    public class Parent 
    { 
     public string item{get;set;} 
    } 

    private class Child : Parent 
    { 
    } 
} 

namespace MainProgram 
{ 
    class Program 
    { 
     public static void ConsoleWrite(Parent pitem) 
     { 
      Console.Write(pitem.item); 
     } 

     public static void Main() 
     { 
      ConsoleWrite(new Child(){item = "foo"}); 
     } 
    } 
} 
0

我修改了一下你的代码来限制它,但它不显示任何编译时错误。引发运行时错误。下面的代码:

using System; 


public class Program 
{ 
public class Parent 
{ 

    public virtual string item{get;set;} 
} 

public class Child : Parent 
{ 

    public new string item 
    { 
     get 
     { 
      throw new NotSupportedException(); 
     } 
     set 
     { 
      throw new NotSupportedException(); 
     } 
    } 

} 

public static void ConsoleWrite(Parent pitem) 
{ 
    Console.Write(pitem.item); 
} 

public static void Main() 
{ 
    ConsoleWrite(new Child(){item = "foo"}); 
} 

}