簡體   English   中英

擴展方法僅限於包含特定屬性的對象

[英]Extension method restricted to objects containing specific properties

有沒有辦法創建一個擴展方法,其參數的唯一約束是具有專門命名的屬性。 例如:

public static bool IsMixed<T>(this T obj) where T:?
{
    return obj.IsThis && obj.IsThat;
} 

我試圖將obj聲明為動態的,但這是不允許的。

此功能通常稱為“鴨子打字”。 (因為當您調用 foo.Quack() 時,您所關心的只是它像鴨子一樣嘎嘎叫。)非動態鴨子類型不是 C# 的功能,抱歉!

如果你真的沒有關於參數的類型信息,你可以在 C# 4 中使用 dynamic:

public static bool IsAllThat(this object x)
{
    dynamic d = x;
    return d.IsThis || d.IsThat;
}

但是最好在編譯時提出一些接口或一些描述類型的東西。

您必須讓 T 實現一個接口,然后在約束中使用它。

雖然您無法使用通用約束做您想要做的事情,但您可以使用反射在運行時檢查類型以確定它是否具有這些屬性並動態獲取它們的值。

免責聲明:我這樣做是出於我的想法,我在實施中可能會稍有偏差。

public static bool IsMixed(this object obj)
{
    Type type = obj.GetType();

    PropertyInfo isThisProperty = type.GetProperty("IsThis", typeof(bool));
    PropertyInfo isThatProperty = type.GetProperty("IsThat", typeof(bool));

    if (isThisProperty != null && isThatProperty != null)
    {
        bool isThis = isThisProperty.GetValue(this, null);
        bool isThat = isThatProperty.GetValue(this, null);

        return isThis && isThat;
    }
    else
    {
        throw new ArgumentException(
            "Object must have properties IsThis and IsThat.",
            "obj"
        );
    }
}

幾乎唯一的方法是將接口作為您要操作的 class 的基礎:

interface iMyInterface
{

}

public static bool IsMixed<T>(this T obj) where T: iMyInterface
{
   return obj.IsThis && obj.IsThat;
} 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM