C# 4.0 通用接口调用出现 NullReferenceException 异常示例
以下是一个示例,展示了如何编写一个通用接口,并在调用接口时出现为 null 的情况:
using System;
public interface IGenericInterface<T>
{
void Print(T value);
}
public class GenericClass<T> : IGenericInterface<T>
{
public void Print(T value)
{
Console.WriteLine(value);
}
}
public class Program
{
public static void Main(string[] args)
{
IGenericInterface<string> myInterface = null;
// 尝试调用接口方法,会引发 NullReferenceException 异常
myInterface.Print('Hello World');
// 输出结果:Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object.
}
}
在上述示例中,我们定义了一个通用接口 IGenericInterface<T>,并实现了一个泛型类 GenericClass<T>,该类实现了接口中的方法。
然后在 Main 方法中,我们创建了一个接口实例 myInterface,并将其设置为 null。
在尝试调用 myInterface.Print('Hello World') 时,由于 myInterface 为 null,会引发 NullReferenceException 异常。
这个案例展示了在调用接口时,如果接口实例为 null,会出现为 null 的情况。
为了避免这种情况,在调用接口方法之前,需要确保接口实例已经被正确初始化,例如:
IGenericInterface<string> myInterface = new GenericClass<string>();
myInterface.Print('Hello World');
这样就可以避免出现 NullReferenceException 异常。
原文地址: https://www.cveoy.top/t/topic/qnMH 著作权归作者所有。请勿转载和采集!