gpt4 book ai didi

c# - 可疑类型转换解决方案中没有继承自两者的类型

转载 作者:行者123 更新时间:2023-12-04 04:21:24 24 4
gpt4 key购买 nike

由于某些要求,我应该将一个类转换为通用接口(interface)。但是我收到 ReSharper 警告“可疑类型转换,解决方案中没有从两者继承的类型”。在运行时,它会导致运行时错误。

我应该这样做,因为我正在使用反射,所以我非常需要这个类型转换。
我的代码如下。任何支持表示赞赏。

    class Program
{
static void Main(string[] args)
{
// prepare class name from string
string propertyNavigationFullName = "ConsoleApp1.Entry";

// Take assembly
Assembly assem = typeof(Entry).Assembly;

// take class type
Type className = assem.GetType(propertyNavigationFullName, true);

// create class instance
IEntitySubMultiLang inst = (IEntitySubMultiLang)Activator.CreateInstance(className);

// prepare Generic Class
Type genericClass = typeof(GenericRepo<>);
Type constructedClass = genericClass.MakeGenericType(className);

// create Generic Class instance
// ERROR OCCUR HERE
IRepo<IEntitySubMultiLang> created = (IRepo<IEntitySubMultiLang>)Activator.CreateInstance(constructedClass);

// I need to use Add method or any other method
created.Add(inst);

}

public interface IEntitySubMultiLang
{
int Id { get; set; }
}

public interface IRepo<TEntity> where TEntity : class, IEntitySubMultiLang
{
void Add(TEntity item);
}

public class GenericRepo<TEntity> : IRepo<TEntity> where TEntity : class, IEntitySubMultiLang
{
public void Add(TEntity item)
{

}
}

public class Entry : IEntitySubMultiLang
{
public int Id { get; set; }
}
}

ScreenShot

最佳答案

如果您考虑一下这意味着什么,您所谈论的类型转换实际上是不正确的,这就是它不起作用的原因。假设您有另一个实现 IEntitySubMultiLang 的类:

public class Foo : IEntitySubMultiLang
{
public int Id { get; set; }
}

如果你通过 Foo 会发生什么?至 _r.Add() ?
_r.Add(new Foo());

这没有任何意义,因为 _rGenericRepo<Entry> ,不知道怎么加 Foo s。这正是安全应该避免的那种情况类型。

更新,基于 OP 编辑

因为您使用反射来生成对象,所以当您调用 _r.Add() 时,您实际上并没有从接口(interface)的类型安全方面获得编译时优势。 .所以接受这个事实,并使用反射来调用 Add方法,而不尝试进行任何转换。
    constructedClass
.GetMethod("Add")
.MakeGenericMethod(className)
.Invoke(created, new object[] { inst });

或者,通过将所有内容放入通用辅助方法并通过反射调用该方法,您很有可能可以简化很多代码,并且仍然可以获得很多类型安全。例如:
static private void AddToRepo<TEntity>() where TEntity : class, IEntitySubMultiLang, new
{
new GenericRepo<TEntity>().Add(new TEntity());
}
    typeof(ConsoleApp1)
.GetMethod("AddToRepo")
.MakeGenericMethod(className)
.Invoke(null, new object[] { /* any parameters? */});

关于c# - 可疑类型转换解决方案中没有继承自两者的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59199163/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com