[英]Extension Methods with Custom Classes
我試圖擴展我的自定義類,並遇到一個無法找到擴展方法的問題。.我擁有並且可以擴展任何內置類甚至是DLL中包含的類。 我不知道這是編譯錯誤還是執行錯誤。 放了一個小程序作為示例,不會編譯。
這是擴展名:
namespace ExtensionMethodTesting.Extension
{
public static class Extension
{
public static void DoSomething(this ExtensionMethodTesting.Blah.CustomClass r)
{
}
}
}
這是自定義類:
namespace ExtensionMethodTesting.Blah
{
public class CustomClass
{
public static void DoNothing()
{
}
}
}
這是調用它的代碼:
using ExtensionMethodTesting.Blah;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ExtensionMethodTesting.Extension;
namespace ExtensionMethodTesting
{
class Program
{
static void Main(string[] args)
{
CustomClass.DoNothing();
CustomClass.DoSomething();
}
}
}
我必須缺少一些東西……無論如何,僅為了澄清的確切錯誤是:
錯誤1'ExtensionMethodTesting.Blah.CustomClass'不包含'DoSomething'的定義c:\\ users \\ damon \\ documents \\ visual studio 2013 \\ Projects \\ ExtensionMethodTesting \\ ExtensionMethodTesting \\ Program.cs 16 25 ExtensionMethodTesting
擴展方法需要一個對象的實例。 您必須new
一個CustomClass
才能使用它。
var custom = new CustomClass();
custom.DoSomething();
看到這個答案 ,為什么會這樣。
您需要實例化CustomClass
的對象才能使用其擴展方法。
CustomClass obj = new CustomClass();
obj.DoSomething();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.