![](/img/trans.png)
[英]LINQ to Entities does not recognize the method 'System.Object Parse(System.Type, System.String)'
[英]How to determine if System.Object is System.Type
我正在為WPF編寫一個通用的IValueConverter,並且我正在努力將值與特定類型進行比較。
我的物體的構成看起來像這樣
public interface IAwesome
{
int AwesomeAmount { get; set; }
}
public class MyAwesomeClass : IAwesome
{
public int AwesomeAmount { get; set; }
}
我的方法看起來像這樣
public bool CompareToType(object value, Type type);
如果我有...
var mac = new MyAwesomeClass();
bool isAwesome = CompareToType(mac, typeof(IAwesome));
同樣我可以寫
var stream = new FileStream();
bool isStream = CompareToType(stream, typeof(Stream));
如何編寫CompareToType方法以確定該類是實現接口還是從基礎對象繼承?
道歉,如果我錯過了一些令人目眩的明顯,但我還是很感激一些幫助:)
也許你正在尋找的is
?
var stream = new FileStream();
bool isStream = stream is Stream;
你也可以試試
isStream = typeOf(Stream).IsAssignableFrom(stream.GetType());
如果我理解正確,你正在尋找:
if (mac is IAwesome) {}
或者:var t = mac as IAwesome; if(t!= null){}
bool isAwesome = mac is IAwesome;
要檢查類是否實現了接口:
var obj = new MyInteracedClass();
typeof(IMyInterface).IsAssignableFrom(obj.GetType());
or
typeof(IMyInterface).IsAssignableFrom(typeof(MyInteracedClass));
簡單的實現是
public bool CompareToType(object obj, Type type)
{
return type != null
&& obj != null
&& type.IsAssignableFrom(obj.GetType());
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.