我正在尝试使用xaml实例化一组对象,如下所示:
package main
import (
"bufio"
"context"
"database/sql"
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"strings"
"sync"
"time"
"googlemaps.github.io/maps"
_ "github.com/lib/pq"
)
var db *sql.DB
var (
apiKey string
dsn string
locationsFile string
)
type HourlyForecast struct {
Type string
Properties Properties
}
type Properties struct {
Periods []Period
}
type Period struct {
Temperature int
}
func main() {
flag.StringVar(&apiKey, "api-key", "", "Google Maps API key")
flag.StringVar(&dsn, "dsn", "", "The database connection string")
flag.StringVar(&locationsFile, "locations", "locations.txt", "The locations file")
flag.Parse()
if apiKey == "" {
apiKey = os.Getenv("GOOGLE_MAPS_API_KEY")
}
if apiKey == "" {
log.Fatal("The --api-key flag or GOOGLE_MAPS_API_KEY env var must be set and non-empty")
}
apiKey = strings.TrimSpace(apiKey)
if dsn == "" {
dsn = os.Getenv("DSN")
}
var err error
db, err = sql.Open("postgres", dsn)
if err != nil {
log.Fatal(err)
}
for {
err := db.Ping()
if err != nil {
log.Println(err.Error())
time.Sleep(3 * time.Second)
continue
}
break
}
data, err := os.Open(locationsFile)
if err != nil {
log.Fatal(err)
}
var locations []string
scanner := bufio.NewScanner(data)
for scanner.Scan() {
locations = append(locations, scanner.Text())
}
var wg sync.WaitGroup
for _, location := range locations {
wg.Add(1)
location := location
go func() {
defer wg.Done()
mc, err := maps.NewClient(maps.WithAPIKey(apiKey))
if err != nil {
log.Fatal(err)
}
r := maps.FindPlaceFromTextRequest{
Input: location,
InputType: maps.FindPlaceFromTextInputTypeTextQuery,
}
response, err := mc.FindPlaceFromText(context.Background(), &r)
if err != nil {
log.Fatal(err)
}
pdr := maps.PlaceDetailsRequest{
PlaceID: response.Candidates[0].PlaceID,
}
log.Printf("retrieving geo coordinates for %s", location)
pdResponse, err := mc.PlaceDetails(context.Background(), &pdr)
if err != nil {
log.Fatal(err)
}
lat := pdResponse.Geometry.Location.Lat
lng := pdResponse.Geometry.Location.Lng
u := fmt.Sprintf("https://api.weather.gov/points/%.4f,%.4f/forecast/hourly", lat, lng)
log.Printf("retrieving weather data for %s (%.4f,%.4f)", location, lat, lng)
request, err := http.NewRequest("GET", u, nil)
if err != nil {
log.Fatal(err)
}
request.Header.Add("User-Agent", "Hightower Weather 1.0")
request.Header.Add("Accept", "application/geo+json")
weatherResponse, err := http.DefaultClient.Do(request)
if err != nil {
log.Fatal(err)
}
data, err := ioutil.ReadAll(weatherResponse.Body)
if err != nil {
log.Fatal(err)
}
weatherResponse.Body.Close()
var forecast HourlyForecast
if err := json.Unmarshal(data, &forecast); err != nil {
log.Fatal(err)
}
log.Printf("setting temperature for %s to %d", location, forecast.Properties.Periods[0].Temperature)
_, err = db.Exec(query, location, forecast.Properties.Periods[0].Temperature)
if err != nil {
log.Fatal(err)
}
}()
}
wg.Wait()
}
var query = `INSERT INTO weather (location, temperature)
VALUES ($1, $2)
ON CONFLICT (location)
DO UPDATE SET temperature = EXCLUDED.temperature;`
第一个实例“ R1”起作用并被实例化。即使没有引发任何错误,其他两个也不是。无论我移至哪种关系,都可以正常工作,因此很显然,它只会“接受”一个实例。我有办法吗?我尝试过尝试创建一个Collection类来保存它们,但没有成功。尝试像这样将集合指定为ContentProperty:
<Application.Resources>
<local:RelationshipDefinition x:Key="R1" Name="College"
Type="One2one" ForwardName="Attended"
/>
<local:RelationshipDefinition x:Key="R2" Name="HasPart"
Type="One2manyBi" ForwardName="Part" BackwardName="PartOf"
/>
<local:RelationshipDefinition x:Key="R3" Name="HasChild"
Type="One2manyBi" ForwardName="Child" BackwardName="Parent"
/>
</Application.Resources>
产生此错误:
[ContentProperty("Definitions")]
我对xaml的方法是陌生的,并且可以想象必须有一些相当简单的方法来实现这一目标。
在我的第一篇文章之后,我发现如果我创建了一个单独的Error CS1729 'ContentPropertyAttribute' does not contain a constructor that takes 1 arguments
来容纳每个ResourceDictionary
并像这样分别包含它们:
RelationshipDefinition
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="HasChildrenRelationship.xaml"/>
<ResourceDictionary Source="CollegeRelationship.xaml"/>
<ResourceDictionary Source="HasPartRelationship.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
对象是一个简单的声明性对象,供基于语义网的数据访问方法使用。每个用户“声明”他们在特定情况下很可能使用的网络关系。这是来自该类的代码片段。基本上,所有依赖项属性都具有在全局存储区中注册/查找RelationshipDefinition
的构造函数。
RelationshipDefinition
它是这样使用的:
public class RelationshipDefinition : DependencyObject
{
public string UID { get; set; } = Guid.NewGuid().ToString();
public string Name
{
get { return (string)GetValue(NameProperty); }
set
{
SetValue(NameProperty, value);
RegisterRelationshipDefinition(this);
}
}
public static readonly DependencyProperty NameProperty =
DependencyProperty.Register("Name", typeof(string), typeof(RelationshipDefinition), new PropertyMetadata(null));
public RelationshipType Type
{
get { return (RelationshipType)GetValue(TypeProperty); }
set { SetValue(TypeProperty, value); }
}
public static readonly DependencyProperty TypeProperty =
DependencyProperty.Register("Type", typeof(RelationshipType), typeof(RelationshipDefinition), new PropertyMetadata(null));
...etc...
所有Person chris = new Person(){ FirstName = "Chris", LastName = "Smith", Age = 19 };
Person annemarie = new Person() {FirstName = "Anne-Marie", LastName = "Smith", Age = 22 };
Person john = new Person() { FirstName = "John", LastName = "Smith", Age = 47};
SNet.Link(from: chris, to: nyu, via: "College");
SNet.Link(from: john, to: chris, via: "HasChild");
SNet.Link(from: john, to: annemarie, via: "HasChild");
Person p1 = SNet.GetBackLink<Person>(from: annemarie, via: "HasChild");
List<Person> children = SNet.GetForwardLinks<Person>(from: john, via: "HasChild");
对象均已正确实例化。我确定必须有一种方法将我想念的东西都包括在内。