- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我有一个 UserControl,它被设计用来编辑一些任意 POCO 的集合。 POCO 是在设计时选择的,因此我可以传递 POCO 中需要显示和编辑的属性的描述,但我正在努力寻找在控件中实例化新 POCO 以添加到集合中的最佳方法。
目前,我正在向包含 IPocoFactory
的控件添加一个新属性,但这似乎并不令人满意,原因如下:
IPocoFactory
接口(interface)的类才能使用控件,否则会非常简单谁能为这个问题提出一个合适的模式?我不可能是唯一一个面对它的人!
我想到反射可能在解决方案中发挥作用,但我对此也不太确定:我可以检查 ItemsSource
(一个非通用的 IEnumerable
) 看看里面有什么,但如果它是空的,就没有什么可看的。
最佳答案
您可以通过调用 ItemsSource.GetType().GetInterfaces()
来获取要创建的类型, 找到 Type
IEnumerable<T>
的对象接口(interface)(任何通用集合都将实现),并调用 GetGenericArguments()
在上面。 IEnumerable<T>
当然,只有一个类型参数,所以这就是您需要创建其实例的类型。
然后 you can create an instance fairly easily (请参阅下面的更新,了解将这一切包装到单个方法调用中的静态方法):
ObjectType instance = (ObjectType)Activator.CreateInstance("AssemblyName",
"MyNamespace.ObjectType");
您需要声明类型的程序集,but that's a property of Type
. Assembly
有a CreateInstance
method以及。这是做同样事情的另一种方法:
Type otype = typeof(ObjectType);
ObjectType instance = (ObjectType)otype.Assembly.CreateInstance(otype.FullName);
如果要实例化的类型没有默认构造函数,这会变得更难看。您必须编写明确的代码来提供值,而且没有办法保证它们有意义。但至少这比给消费者带来的负担要轻得多 IPOCOFactory
实现。
顺便记住System.String
没有默认构造函数。用 List<String>
测试下面的代码是很自然的,但这会失败。
一旦你有了 ItemsSource
中的对象类型,您可以通过以编程方式枚举属性的名称和类型以及自动生成列来进一步简化维护。如果需要,您可以写一个 Attribute
类来控制显示哪些,提供显示名称等。
这是一个粗略的实现,它可以让我创建在不同程序集中声明的类的实例:
/// <summary>
/// Collection item type must have default constructor
/// </summary>
/// <param name="items"></param>
/// <returns></returns>
public static Object CreateInstanceOfCollectionItem(IEnumerable items)
{
try
{
var itemType = items.GetType()
.GetInterfaces()
.FirstOrDefault(t => t.Name == "IEnumerable`1")
?.GetGenericArguments()
.First();
// If it's not generic, we may be able to retrieve an item and get its type.
// System.Windows.Controls.DataGrid will auto-generate columns for items in
// a non-generic collection, based on the properties of the first object in
// the collection (I tried it).
if (itemType == null)
{
itemType = items.Cast<Object>().FirstOrDefault()?.GetType();
}
// If that failed, we can't do anything.
if (itemType == null)
{
return null;
}
return itemType.Assembly.CreateInstance(itemType.FullName);
}
catch (Exception ex)
{
return null;
}
}
public static TestCreate()
{
var e = Enumerable.Empty<Foo.Bar<Foo.Baz>>();
var result = CreateInstanceOfCollectionItem(e);
}
你可以制作CreateInstanceOfCollectionItem()
IEnumerable
上的扩展方法如果你喜欢:
var newItem = ItemsSource?.CreateInstanceOfCollectionItem();
这取决于实际集合是否为通用集合,但它不关心您对集合的引用 类型。 ItemsControl.ItemsSource
类型为 System.Collections.IEnumerable
,因为任何标准泛型集合都支持该接口(interface),因此可以转换为它。但是调用GetType()
在该非通用接口(interface)引用上将返回引用另一端(可以这么说)对象的实际运行时类型:
var ienumref = (new List<String>()) as System.Collections.IEnumerable;
// fullName will be "System.Collections.Generic.List`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]"
// ...or something like it, for whatever version of .NET is on the host.
var fullName = ienumref.GetType().Name;
关于c# - 我应该如何实例化一个未知类型的类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37974483/
我正在尝试在Elasticsearch中返回的值中考虑地理位置的接近性。我希望近距离比某些字段(例如legal_name)重要,但比其他字段重要。 从文档看来,当前的方法是使用distance_fea
我是Elasticsearch的初学者,今天在进行“多与或”查询时遇到问题。 我有一个SQL查询,需要在Elastic中进行转换: WHERE host_id = 999 AND psh_pid =
智能指针应该/可以在函数中通过引用传递吗? 即: void foo(const std::weak_ptr& x) 最佳答案 当然你可以通过const&传递一个智能指针。 这样做也是有原因的: 如果接
我想执行与以下MYSQL查询等效的查询 SELECT http_user, http_req_method, dst dst_port count(*) as total FROM my_table
我用这两个查询进行测试 用must查询 { "size": 200, "from": 0, "query": { "bool": { "must": [ { "mat
我仍在研究 Pro Android 2 的简短服务示例(第 304 页)同样,服务示例由两个类组成:如下所示的 BackgroundService.java 和如下所示的 MainActivity.j
给定标记 like this : header really_wide_table..........................................
根据 shouldJS 上的文档网站我应该能够做到这一点: ''.should.be.empty(); ChaiJS网站没有使用 should 语法的示例,但它列出了 expect 并且上面的示例似乎
我在 Stack Overflow 上读到一些 C 函数是“过时的”或“应该避免”。你能给我一些这种功能的例子以及原因吗? 这些功能有哪些替代方案? 我们可以安全地使用它们 - 有什么好的做法吗? 最
在 C++11 中,可变参数模板允许使用任意数量的参数和省略号运算符 ... 调用函数。允许该可变参数函数对每个参数做一些事情,即使每个参数的事情不是一样的: template void dummy(
我在我从事的项目之一上将Shoulda与Test::Unit结合使用。我遇到的问题是我最近更改了此设置: class MyModel :update end 以前,我的(通过)测试看起来像这样: c
我该如何做 or使用 chai.should 进行测试? 例如就像是 total.should.equal(4).or.equal(5) 或者 total.should.equal.any(4,5)
如果您要将存储库 B 中的更改 merge 到存储库 A 中,是否应该 merge .hgtags 中的更改? 存储库 B 可能具有 A 中没有的标签 1.01、1.02、1.03。为什么要将这些 m
我正在尝试执行X AND(y OR z)的查询 我需要获得该代理为上市代理或卖方的所有已售属性(property)。 我只用 bool(boolean) 值就可以得到9324个结果。当我添加 bool
我要离开 this教程,尝试使用 Mocha、Supertest 和 Should.js 进行测试。 我有以下基本测试来通过 PUT 创建用户接受 header 中数据的端点。 describe('U
我正在尝试为 Web 应用程序编写一些 UI 测试,但有一些复杂的问题希望您能帮助我解决。 首先,该应用程序有两种模式。其中一种模式是“训练”,另一种是“现场”。在实时模式下,数据直接从我们的数据库中
我有一个规范: require 'spec_helper' # hmm... I need to include it here because if I include it inside desc
我正在尝试用这个测试我在 Rails 中的更新操作: context "on PUT to :update" do setup do @countdown = Factory(:count
我还没有找到合适的答案: onclick="..." 中是否应该转义 &(& 符号)? (或者就此而言,在每个 HTML 属性中?) 我已经尝试在 jsFiddle 和 W3C 的验证器上运行转义和非
import java.applet.*; import java.awt.*; import java.awt.event.*; public class Main extends Applet i
我是一名优秀的程序员,十分优秀!