C# 使用类型类的属性作为参数

C# 使用类型类的属性作为参数,c#,.net,class,C#,.net,Class,下面我有一个类,它的属性类型是另一个类: ParentClass parentClass = new ParentClass(); public class ParentClass { public NestedClass nestedClassProperty { get; set; } } 下面是用作ParentClass中属性的类: public class NestedClass { public str

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

    ParentClass parentClass = new ParentClass();

    public class ParentClass
    {
        public NestedClass nestedClassProperty { get; set; }
    }
下面是用作ParentClass中属性的类:

    public class NestedClass
    {
        public string someProperty { get; set; }
    }
如何将nestedClassProperty传递给只接受父类之外的属性的方法?请参见以下示例:

    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. */
    }

提前谢谢

与任何其他方法签名一样,参数应为预期类型:

public void method2(ParentClass.NestedClass nestedClassObject)
{
    // ...
}
对于嵌套在另一个类中的类,类型限定符只是
OuterClass.InnerClass

编辑:如果可以有多个嵌套类,则需要以某种方式将它们分组,可以作为参数类型,也可以作为泛型方法上的类型约束。嵌套类本身的性质对于类型系统在结构上并不重要

请注意您在此处的陈述:

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

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

public interface INestedClass
{
    // declare the identical members
}
public class ParentClass
{
    // etc.

    public class NestedClass : INestedClass
    {
        // implement the interface
    }
}
public void method2(INestedClass nestedClassObject)
{
    // ...
}
然后嵌套类将实现该接口:

public interface INestedClass
{
    // declare the identical members
}
public class ParentClass
{
    // etc.

    public class NestedClass : INestedClass
    {
        // implement the interface
    }
}
public void method2(INestedClass nestedClassObject)
{
    // ...
}
然后,方法参数将是接口的:

public interface INestedClass
{
    // declare the identical members
}
public class ParentClass
{
    // etc.

    public class NestedClass : INestedClass
    {
        // implement the interface
    }
}
public void method2(INestedClass nestedClassObject)
{
    // ...
}
接口本身也可能像任何其他类一样嵌套


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

为什么不让method2将父类作为其参数并检查nestedClassProperty的值?为什么不定义所需的接口。那么就不要假设哪个类impl实际上被传入了?您真的不应该假设什么将传递到公共方法中;否则,您将发现单元测试非常困难。很抱歉没有澄清,但是“method2”需要接受ParentClass中的任何嵌套类。@Cryptonaut:在这种情况下,您需要一些常见类型,例如接口。我已经相应地更新了我的答案。