![](/img/trans.png)
[英]How do I make a class that can create an instance of another class and access private members of the owner
[英]Create new instance of private class in another private class
是否可以在另一個私有類中創建一個私有類的實例? (不計入main()程序中。)而且,私有類中的方法是否可能返回私有類型對象?
之所以問這個問題,是因為我在C#5的C#基礎上關注PluralSight的Scott Allen。 在關於類和對象的第二課中,他有一個如下代碼示例:
public GradeStatistics ComputeStatistics()
{
GradeStatistics stats = new GradeStatistics();
...
...
}
在單獨的類文件中定義的GradeStatistics如下:
class GradeStatisticss
{
}
內聯評論:我不是在談論嵌套類。 我的意思是,您有兩個類(單獨的文件),我想知道一個類是否可以創建另一個類的實例(知道它們都是私有的)。
Edited with examples:
private class Example1
{
}
private class Example2
{
public Example1 DoSomeComputation()
{
return new Example1();
}
}
private class Example3
{
Example1 ex1 = new Example1();
}
Is Example3 able to create ex1? Can Example2 return a new instance of Example1?
是否可以在另一個私有類中創建一個私有類的實例?
僅在要創建實例的私有類中聲明了要為其創建實例的私有類時。 如果未嵌套,則不可能。
私有類中的方法是否可以返回私有類型對象?
是的,它可以。
這是一些將所有內容一起顯示的代碼:
public class Tester {
private class ThePrivateCreator {
private class TheOtherPrivateClass {
}
public Object createObject() {
return new TheOtherPrivateClass();
}
}
public void canWeDoThis() {
ThePrivateCreator c = new ThePrivateCreator();
Console.WriteLine(c.createObject());
}
}
class Program
{
public static void Main(string[] args) {
Tester t = new Tester();
t.canWeDoThis();
}
}
不能。私有類不能被另一個文件中的另一個類訪問。 其原因是修飾符private旨在將數據或方法封裝在該類內部。 如果要從另一個未嵌套的類訪問一個類,則應使用public或internal修飾符。 如果是嵌套的,則還可以使用protected修飾符。
不確定您的初衷是什么,但這是一個可能的示例:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication26
{
class Program
{
static void Main(string[] args)
{
private1 p1 = new private1();
private2 p2 = p1.foo();
Console.WriteLine(p2.Value);
Console.ReadLine();
}
private class private1
{
public private2 foo()
{
private2 p2 = new private2("I was created inside a different private class!");
return p2;
}
}
private class private2
{
private string _value;
public string Value
{
get { return _value; }
}
public private2(string value)
{
this._value = value;
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.