使用类型class的属性作为参数

本文关键字:参数 属性 类型 class | 更新日期: 2023-09-27 18:06:27

下面我有一个类,它有一个属性的类型是另一个类:

    ParentClass parentClass = new ParentClass();
    public class ParentClass
    {
        public NestedClass nestedClassProperty { get; set; }
    }

下面是在ParentClass中用作属性的类:

    public class NestedClass
    {
        public string someProperty { get; set; }
    }

我如何传递nestedClassProperty到一个方法,只接受属性是ParentClass的一部分?请看下面的例子:

    public void method1()
    {
        method2(parentClass.nestedClassProperty);
    }
    public void method2(/* Parameter should accept the nestedClassProperty
                           within ParentClass Note: This method should also                 
                           accept any other property within ParentClass   
                           that's type is of another class. */)
    {
        /* Do something with nestedClassProperty.
           Note: Every class that's nested as a property 
           within ParentClass will have identical properties. */
    }

提前感谢!

使用类型class的属性作为参数

就像任何其他方法签名一样,参数的类型应该是预期的:

public void method2(ParentClass.NestedClass nestedClassObject)
{
    // ...
}

对于嵌套在另一个类中的类,类型限定符仅为OuterClass.InnerClass

Edit:如果可以有多个嵌套类,那么您需要以某种方式对它们进行分组,要么作为参数类型,要么作为泛型方法的类型约束。嵌套类本身的性质对类型系统在结构上并不重要。

注意这里的表述:

注意:每个嵌套类都有相同的属性。

这看起来像是一个接口的作业:

public interface INestedClass
{
    // declare the identical members
}

那么嵌套类将实现该接口:

public class ParentClass
{
    // etc.
    public class NestedClass : INestedClass
    {
        // implement the interface
    }
}

方法参数将属于接口:

public void method2(INestedClass nestedClassObject)
{
    // ...
}

接口本身也可以像其他类一样嵌套。

本质上你要找的是教科书上的多态性。任何给定类型是否嵌套在另一个类型中都没有区别。