Большинство предлагаемых ответов создают дополнительный временный скрытый элемент ввода. Поскольку большинство браузеров в настоящее время поддерживают редактирование содержимого div, я предлагаю решение, которое не создает скрытые элементы, сохраняет форматирование текста и использует чистую библиотеку JavaScript или jQuery.
Вот минимальная реализация скелета с использованием наименьших строк кодов, которые я мог бы подумать:
//Pure javascript implementation:
document.getElementById("copyUsingPureJS").addEventListener("click", function() {
copyUsingPureJS(document.getElementById("copyTarget"));
alert("Text Copied to Clipboard Using Pure Javascript");
});
function copyUsingPureJS(element_id) {
element_id.setAttribute("contentEditable", true);
element_id.setAttribute("onfocus", "document.execCommand('selectAll',false,null)");
element_id.focus();
document.execCommand("copy");
element_id.removeAttribute("contentEditable");
}
//Jquery:
$(document).ready(function() {
$("#copyUsingJquery").click(function() {
copyUsingJquery("#copyTarget");
});
function copyUsingJquery(element_id) {
$(element_id).attr("contenteditable", true)
.select()
.on("focus", function() {
document.execCommand('selectAll', false, null)
})
.focus()
document.execCommand("Copy");
$(element_id).removeAttr("contenteditable");
alert("Text Copied to Clipboard Using jQuery");
}
});
#copyTarget {
width: 400px;
height: 400px;
border: 1px groove gray;
color: navy;
text-align: center;
box-shadow: 0 4px 8px 0 gray;
}
#copyTarget h1 {
color: blue;
}
#copyTarget h2 {
color: red;
}
#copyTarget h3 {
color: green;
}
#copyTarget h4 {
color: cyan;
}
#copyTarget h5 {
color: brown;
}
#copyTarget h6 {
color: teal;
}
#pasteTarget {
width: 400px;
height: 400px;
border: 1px inset skyblue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="copyTarget">
<h1>Heading 1</h1>
<h2>Heading 2</h2>
<h3>Heading 3</h3>
<h4>Heading 4</h4>
<h5>Heading 5</h5>
<h6>Heading 6</h6>
<strong>Preserve <em>formatting</em></strong>
<br/>
</div>
<button id="copyUsingPureJS">Copy Using Pure JavaScript</button>
<button id="copyUsingJquery">Copy Using jQuery</button>
<br><br> Paste Here to See Result
<div id="pasteTarget" contenteditable="true"></div>
При помощи отражения можно сделать это. В C# это похоже на это;
PropertyInfo[] propertyInfo = myobject.GetType().GetProperties();
<час> Добавленный перевод VB.Net:
Dim info() As PropertyInfo = myobject.GetType().GetProperties()
Можно использовать Система. Отражение пространство имен для запросов информации о типе объекта.
For Each p As System.Reflection.PropertyInfo In obj.GetType().GetProperties()
If p.CanRead Then
Console.WriteLine("{0}: {1}", p.Name, p.GetValue(obj, Nothing))
End If
Next
Обратите внимание на то, что не предлагается использовать этот подход вместо наборов в Вашем коде. Отражение является производительностью интенсивная вещь и должно использоваться мудро.
Можно использовать отражение... С Отражением можно исследовать каждого члена класса (Тип), proeprties, методы, конструкторы, поля, и т.д.
using System.Reflection;
Type type = job.GetType();
foreach ( MemberInfo memInfo in type.GetMembers() )
if (memInfo is PropertyInfo)
{
// Do Something
}