![](/img/trans.png)
[英]C# why using reflection get field object, the first field are from child object and then from base class
[英]I can't get value of base class field from child class object in c#
using System;
public class Program
{
public static void Main()
{
CloudCollectionHelper cloudHelper = new CloudCollectionHelper();
SlackHelper slackHelper = new SlackHelper();
cloudHelper.DatabaseID=12345;
Console.WriteLine(slackHelper.GetSlackPageTokens());
}
class CloudCollectionHelper
{
public long DatabaseID { get; set; }
}
class SlackHelper:CloudCollectionHelper
{
public long GetSlackPageTokens()
{
return DatabaseID;
}
}
}
當前 output:0 預期 Output:12345
我需要 output 12345 因為來自 cloudhelper 的 DatabaseID,所以我需要 slackhelper 中的 databaseID。
這是我的 c# 在線編譯器: https://dotnetfiddle.net/QNQeEX
子 class 沒有從基礎 class 獲得分配的值。 因為它可能有多個實例。 例如,如果您有
...
CloudCollectionHelper cloudHelper1 = new CloudCollectionHelper();
CloudCollectionHelper cloudHelper2 = new CloudCollectionHelper();
cloudHelper1.DatabaseID = 1234;
cloudHelper2.DatabaseID = 6789;
Console.WriteLine(slackHelper.GetSlackPageTokens()); //It would not know, what value to use.
...
最好的方法是將值直接分配給子 class 或使用 static 修飾符。
編輯:如果您需要從子 class 獲取此值,無論出於何種原因,最好的方法是這樣做:
...
CloudCollectionHelper cloudHelper = new CloudCollectionHelper();
cloudHelper.DatabaseID = 12345; //First assign the needed Value
SlackHelper slackHelper = new SlackHelper(cloudHelper); //then create a new instance from the child class
...
並從 SlackHelper 子 class 添加構造函數,如下所示:
class SlackHelper:CloudCollectionHelper
{
public SlackHelper(CloudCollectionHelper cloudHelper)
{
this.DatabaseID = cloudHelper.DatabaseID;
}
... //Do everything else what this class needs here
}
如果來自 cloudHelper.DatabaseID 的值可以在運行時更新,您將需要一個事件來更新子 class。 這仍然不是最好的方法,因為 DatabaseID 值已經是公共的,並且可以在沒有子 class 的情況下訪問。
編輯 2:就像我在評論中已經告訴你的那樣,你也可以使用 static 修飾符來避免這個問題。 但這將影響由 CloudCollectionHelper class 創建的每個實例。 一旦您將其設為 static,這將只為所有實例保留 1 個可能的值。
(請記住,如果需要或最好的情況下使用評論,請避免使用幻數)
您的 Object slackhelper 的屬性沒有受到影響。 您無需創建 CloudCollectionHelper Object。
SlackHelper slackHelper = new SlackHelper();
slackHelper.DatabaseID=12345;
Console.WriteLine(slackHelper.GetSlackPageTokens());
您應該在 class 中創建此屬性以允許讀取數據庫 ID
public long GetSlackPageTokens() { return base.DatabaseID; }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.