我已經從真實的代碼中提取了這個,并且只是實作了一些東西來給它提供背景關系(我希望如此)。我在遞回呼叫的行上收到以下錯誤GetResourceVariable
CS1503: Argument 1: cannot convert from `CResourceGroup` to `TResource`
Argument type `CResourceGroup` is not assignable to parameter type `TResource`
我想要做的是呼叫GetResourceVariableTResource 型別的物件來獲取某個變數值。這些物件是層次結構的一部分,因此如果未在資源上定義變數,我想遍歷層次結構并查看“父級”是否定義了此變數并回傳該值。這就是 FromResource 的用武之地。現在這個 FromResource 應該是一個組/檔案夾型別的資源,但它具有資源的許多屬性,您可以從類繼承層次結構中看到這些屬性。
我不明白為什么我不能使用 CResourceGroup(這是一個 CResDefs,它是一個 CResource 作為通用函式的引數,where TResource : CResource我認為where約束意味著只有 CResource 的物件(或從 CResource 繼承)可能是引數嗎?不知何故,最后一部分似乎不正確!
我可能能夠重構繼承層次結構,但在嘗試之前我寧愿知道為什么這不可能,如 C# 所示?
using System;
using System.Collections.Generic;
public class Program
{
public class CResVariable
{
public string Value { get; set; }
}
public class CResVariableList : List<CResVariable>
{
public CResVariable GetByName(string name) { return null; }
}
public class CResource {
public CResVariableList ResVariables { get; set; }
public CResourceGroup FromResource
{
get
{
return this.GetFromResource(useChildrenList:true);
}
}
protected CResourceGroup GetFromResource(bool useChildrenList = false)
{
return null;
}
}
public class CResDefs : CResource {}
public class CResourceGroup : CResDefs {}
public class ResVariableSupport {
public string GetResourceVariable<TResource>(TResource resource, string variableName, bool recursive)
where TResource : CResource
{
CResVariable variable = resource?.ResVariables?.GetByName(variableName);
if (variable != null)
{
return variable.Value;
}
if (recursive)
{
return this.GetResourceVariable<TResource>(resource?.FromResource, variableName, true);
}
return "";
}
}
public static void Main() {
Console.WriteLine("Hello world!");
}
}
uj5u.com熱心網友回復:
您的代碼中唯一的問題是在呼叫中明確命名通用引數GetResourceVariable- 您不需要這樣做,因為它是從呼叫中暗示的。
這有效:
return this.GetResourceVariable(resource?.FromResource, variableName, true);
此處代碼:https ://dotnetfiddle.net/LxUIxL
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/511722.html
標籤:C#仿制药遗产
上一篇:為什么我不能直接記住mutableStateOf可組合函式?
下一篇:Scala-物件和類
