很直接的問題。我只想在輸入中允許 DTO 模型(類和記錄型別)。
如果我只留下class約束,我仍然可以放在string那里。我不想允許原始型別。
如果我放class, new(),它不會string像預期的那樣允許,但我也不允許使用位置記錄,這是一個問題。
public class Asd
{
public string Name { get; set; }
}
public record Asd2(string Name);
public Task DoSomethingAsync<TInput>(TInput data) where TInput : class
{
var message = JsonSerializer.Serialize(data); // if TInput is a string, it results into faulty \u0022 codes
}
編輯:實際的問題是我JsonSerializer.Serialize(data)在那個方法里面,如果 astring被意外傳遞,它會導致類似的結果:
"{\u0022Name\u0022:\u0022Test\u0022}"
uj5u.com熱心網友回復:
您需要對限制具有某種共性。這需要是一個通用的基類或介面。
由于您也想使用 Records,那么這必須是一個介面。但是,如果您只是為了這個目的,您可以定義一個簡單的、空的。
所以你定義了一個簡單的空介面(如果你真的有一些通用的函式/屬性更好)。
public interface MyInterface
{
}
那么你的代碼看起來像這樣
public Task DoSomethingAsync<TInput>(TInput data) where TInput : MyInterface
{
}
你所有的類和記錄都是這樣繼承的。
public record AsdRecord: MyInterface
{
//details here
}
public class AsdClass: MyInterface
{
//details here
}
uj5u.com熱心網友回復:
如果您的允許型別串列不能使用型別約束來制定,請考慮創建一個允許型別串列(在代碼中硬編碼或在運行時使用反射,例如在命名空間上)并在運行時針對該串列進行測驗該方法(就像您還測驗傳入引數一樣)。也許是這樣的
private static readonly HashSet<Type> AllowedTypes = new HashSet<Type>
{
typeof(MyTypeA),
typeof(MyTypeB),
};
public Task DoSomethingAsync<TInput>(TInput data)
{
if(!AllowedTypes.Contains(typeof(TInput)))
throw new ArgumentException($"The type {typeof(TInput).Name} can' t be used here.");
// ...
}
雖然這在編譯時對您沒有幫助,但至少在運行時對您有所幫助。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/460213.html
