c#中泛型委托的问题
本文关键字:问题 泛型 | 更新日期: 2023-09-27 18:01:51
我有一个示例程序,其中我有一个名为ObserverTest
的类,其中我有两个方法
一个用于订阅,一个用于任何类型T的通知,但我得到一些构建错误。
下面是我的示例代码>
using System;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
ObserverTest obs = ObserverTest.Instance();
obs.SubscribeToChange<int>(GotChange);
obs.NotifyChange<int>(200);
Console.ReadLine();
}
private static void GotChange(int val)
{
Console.WriteLine(string.Format("Changed value is {0}", val));
}
}
public class ObserverTest
{
private static ObserverTest _obsTest;
private Action<T> _observer;
private ObserverTest()
{
}
public static ObserverTest Instance()
{
return _obsTest = _obsTest == null ? new ObserverTest() : _obsTest;
}
public void NotifyChange<T>(T val)
{
_observer(val);
}
public void SubscribeToChange<T>(Action<T> observer)
{
_observer = observer;
}
}
}
和以下是错误:
Error 1 The type or namespace name 'T' could not be found (are you missing a using directive or an assembly reference?) C:'Users'Administrator'AppData'Local'Temporary Projects'ConsoleApplication1'Program.cs 24 22 ConsoleApplication1
Error 2 The field 'ConsoleApplication1.ObserverTest._observer' cannot be used with type arguments C:'Users'Administrator'AppData'Local'Temporary Projects'ConsoleApplication1'Program.cs 37 10 ConsoleApplication1
谁能帮我去掉这些错误?
尝试在类定义中添加泛型:
public class ObserverTest<T>
完整代码:
using System;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
ObserverTest<int> obs = ObserverTest<int>.Instance();
obs.SubscribeToChange<int>(GotChange);
obs.NotifyChange<int>(200);
Console.ReadLine();
}
private static void GotChange(int val)
{
Console.WriteLine(string.Format("Changed value is {0}", val));
}
}
public class ObserverTest<T>
{
private static ObserverTest<T> _obsTest;
private Action<T> _observer;
private ObserverTest()
{
}
public static ObserverTest<T> Instance()
{
return _obsTest = _obsTest == null ? new ObserverTest<T>() : _obsTest;
}
public void NotifyChange<E>(T val)
{
_observer(val);
}
public void SubscribeToChange<E>(Action<T> observer)
{
_observer = observer;
}
}
}
如果您有一个泛型成员,如_observer
,则需要在ObserverTest
类上添加类型参数,如下所示:
public class ObserverTest<T> {
}
当然,您还需要修改您的Instance
方法。
您遇到的问题是,您正在声明具有泛型类型的字段成员,而类没有:
public class ObserverTest
{
private static ObserverTest _obsTest;
private Action<T> _observer;
...
}
因此,当您尝试创建ObserverTest
类的实例时,它会尝试设置字段成员,并遇到不知道_observer
具体类型的问题。
要解决这个问题,你必须用泛型参数和任何实例化类的调用来定义类:
public class ObserverTest<T>
{
private static ObserverTest _obsTest;
private Action<T> _observer;
public static ObserverTest<T> Instance<T>()
{
...
}
...
}