Type T must be a reference type in order to use it as a parameter when using the interface

I got an error for the code below

public static Moq.Mock<T> CreateInstanceOfIMock<T>() {
    return new Moq.Mock<T>();
}

I have resolved the error using the specified type class. See below code

public static Moq.Mock<T> CreateInstanceOfIMock<T>() where T : class
{
    return new Moq.Mock<T>();
}

Now I want to move this code var mockColorsRepository = new Moq.Mock<IColorsRepository>();to a generic code with generics. there IColorsRepositoryis interface. So I made a link to the interface for Tinstead class, like this code below

public static Moq.Mock<T> CreateInstanceOfIMock<T>() where T : interface
{
    return new Moq.Mock<T>();
}

But I get an error The type T must be a reference type in order to use it as parameter. How can I refer interfaceinstead classto T. How can I achieve this?

+4
source share
2 answers

class struct generic type constaints , class struct, . , (class) (struct).

, where T : class, , T , , T . struct .

, , . , .

Moq , , :

public static Moq.Mock<T> CreateInstanceOfIMock<T>()
    where T : class
{
    return new Moq.Mock<T>();
}

, , . , CreateInstanceOfIMock<IColorsRepository>() .

, , .

+5

# , . where T : class " T " - .

, T , , typeof(T) , , .

, "" , :

var mock = Helper.CreateInstanceOfIMock<Foo>();

var mock = new Moq.Mock<Foo>();

( Mock<T> -), using Moq;

var mock = new Mock<T>();

... , , - , , .

+5

Source: https://habr.com/ru/post/1690048/


All Articles