相关疑难解决方法(0)

使用反射来查找实现的接口

我有以下情况:

public interface IPerson { .. }    
public class Person : IPerson { .. }    
public class User : Person { .. }
Run Code Online (Sandbox Code Playgroud)

现在; 如果我有一个"用户"对象 - 我如何检查这是否使用反射实现IPerson?更确切地说,我有一个可能具有属性SomeUser的对象,它应该是某种类型,实现接口"IPerson".在我的情况下,我实际上有一个用户,但这是我想通过反思检查.我无法弄清楚如何检查属性类型,因为它是一个"用户",但我想检查它是否实现了IPerson ...:

var control = _container.Resolve(objType); // objType is User here
var prop = viewType.GetProperty("SomeUser");
if ((prop != null) && (prop.PropertyType is IPerson)) 
{ .. }
Run Code Online (Sandbox Code Playgroud)

(请注意,这是我实际情况的简化,但重点应该相同......)

.net c# reflection

23
推荐指数
2
解决办法
2万
查看次数

.NET - 获取通用接口的所有实现?

关于" 通过反射实现接口 "的答案显示了如何获得接口的所有实现.但是,给定通用接口,IInterface<T>以下不起作用:

var types = TypesImplementingInterface(typeof(IInterface<>))
Run Code Online (Sandbox Code Playgroud)

任何人都可以解释我如何修改该方法?

.net c# generics reflection interface

20
推荐指数
1
解决办法
5118
查看次数

DataContract序列化抽象类

我有一个接口IServiceInfo和一个抽象类ServiceInfo.有几个继承自ServiceInfo的类,如CoreServiceInfo,ModuleServiceInfo等.有一个名为RootService的服务契约,它返回IServiceInfo.

 public IServiceInfo GetServiceInfo()
 {
     return (IServiceInfo)new CoreServiceInfo();
 }
Run Code Online (Sandbox Code Playgroud)

我有序列化问题.我可以使用ServiceKnownType来标识基类,使用KnownType来标识子类.

问题是我不知道所有的ServiceInfo子节点,因为应用程序可以有从ServiceInfo继承的不同子节点的插件,所以我无法告诉序列化器将序列化XML中的所有子节点.

我可以忽略抽象类,但它包含某些常见的实现,所以我需要保留它.作为一种解决方法,我可以让另一个类说"sampleServiceInfo"并将所有info类转换为sampleServiceInfo并从Service方法返回它,并将KnownType定义为ServiceInfo类.

[KnownType(typeof(sampleServiceInfo))]
public class ServiceInfo : IServiceInfo
Run Code Online (Sandbox Code Playgroud)

但这听起来并不是很好的方式.请建议.我需要编写自定义序列化程序吗?是否有任何方法只能序列化基数并忽略孩子,当两者都有相同的成员?

c# wcf serialization abstract

6
推荐指数
1
解决办法
3229
查看次数

标签 统计

c# ×3

.net ×2

reflection ×2

abstract ×1

generics ×1

interface ×1

serialization ×1

wcf ×1