我有一个通用类型如下
public class TestGeneric<T>
{
public T Data { get; set; }
public TestGeneric(T data)
{
this.Data = data;
}
}
Run Code Online (Sandbox Code Playgroud)
如果我现在有一个对象(来自某个外部源)我知道它的类型是一些封闭的TestGeneric <>,但我不知道TypeParameter T.现在我需要访问我的对象的数据.问题是我无法强制转换对象,因为我不确切知道哪个封闭的TestGeneric.
我用
// thx to http://stackoverflow.com/questions/457676/c-reflection-check-if-a-class-is-derived-from-a-generic-class
private static bool IsSubclassOfRawGeneric(Type rawGeneric, Type subclass)
{
while (subclass != typeof(object))
{
var cur = subclass.IsGenericType ? subclass.GetGenericTypeDefinition() : subclass;
if (rawGeneric == cur)
{
return true;
}
subclass = subclass.BaseType;
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
为了确保,我的对象是泛型类型.有问题的代码如下:
public static void Main()
{
object myObject = new TestGeneric<string>("test"); // or from another …Run Code Online (Sandbox Code Playgroud) 我正在后台连接我的蓝牙 BLE 设备。因此,我需要在后面的代码中获取蓝牙 mac 地址,就像我们在 XAML 中显示 mac 地址一样。
ListView x:Name="lv" ItemSelected="lv_ItemSelected" BackgroundColor="White" SeparatorColor="Aqua">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout>
<Label TextColor="Black" Text="{Binding NativeDevice.Address}"/>
<Label TextColor="Black" Text="{Binding NativeDevice.Name}"/>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
Run Code Online (Sandbox Code Playgroud)
所以在我们的 xaml 中,我能够在 NativeDevice.Address 中获取 mac 地址。因此,我需要以同样的方式将其放入我的 xaml.cs 中。我可以通过这种方法获取mac地址
var vailditems = adapter.DiscoveredDevices.Where(i => i.NativeDevice.ToString()
Run Code Online (Sandbox Code Playgroud)
但这不是一个好方法,我需要像我的 xaml 一样获取 NativeDevice.Address 中的 mac 地址。我尝试了这种方法,但它给出的地址为空。
public class NativeDevice
{
public string Name { get; set; }
public string Address { get; set; }
}
NativeDevice V = new NativeDevice();
Baddress = V.Address; …Run Code Online (Sandbox Code Playgroud)