簡體   English   中英

需要幫助在 C# 中使用 generics 和 lambda 表達式創建擴展方法

[英]Need help creating extension method in C# with generics and lambda expression

我將所有的高級功能都整合到了一起,但還沒有使用 generics 或 lambda 表達式:

這是我要創建的方法的示例用法:

MyClass mc = null;
int x = mc.TryGetOrDefault(z => z.This.That.TheOther); // z is a reference to mc
// the code has not failed at this point and the value of x is 0 (int's default)
// had mc and all of the properties expressed in the lambda expression been initialized
// x would be equal to mc.This.That.TheOther's value

這是據我所知,但 Visual Studio 抱怨:

在此處輸入圖像描述

您還沒有在TResult您的方法通用。 你想要這樣的東西:

public static TResult TryGetOrDefault<TSource, TResult>
    (this TSource obj, Expression<Func<TSource, TResult>> expression)

暫無
暫無

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

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